May 25, 2015

Suppose that you have an interface named IMyinterface in which four methods are available namedmethod1 (), method2 (), method3 (), method4 () and there are two classes named Base and Derived. As a c# developer you have to implement method1 () and method2 () in class Base and remaining two in Derived. How will you do that give example?

There is basic rule of interface that if any class implements the interface, that class should provide the definition of all the method of interface.But for solving the above scenario if we declare one class as abstract class then it is possible. Here is the example.
using System;

namespace CareerRideTest
{
interface IMyinterface
{
void method1();
void method2();
void method3();
void method4();

}
abstract class Base : IMyinterface
{
public void method1()
{
Console.WriteLine("method1");
}
public void method2()
{
Console.WriteLine("method2");
}
public abstract void method3();
public abstract void method4();
}
class Derived : Base
{
public override void method3()
{
Console.WriteLine("method3");
}
public override void method4()
{
Console.WriteLine("method4");
}
}
class MainClass
{

static void Main(string[] args)
{
Derived obj = new Derived();
obj.method1();
obj.method2();
obj.method3();
obj.method4();
Console.ReadKey();
}
}
}



Output
method1
method2
method3
method4

No comments:

Post a Comment