Interfaces are used to describe a common set of methods. An interface in or of itself cannot be instantiated, but it can be used as a base class. In fact, only interfaces can be used in multiple inheritance of a derived class.
| Caution |
Be very careful when you derive a new class from two interfaces that contain the same method signatures. Under these circumstances, you must use explicit interface implementation, as well as make sure you call the method using a reference type of that interface. |
If you derive a new class from interfaces with the same method signatures, you must use explicit interface implementation, and then call the method using a reference type of that interface. For example, suppose you derived a class like this:
interface IFoo
{
void DoSomething()
}
interface IFoo2
{
void DoSomething()
}
public class MyFoo : IFoo, IFoo2
{
void IFoo.DoSomething()
{
//Do work
}
void IFoo2.DoSomething()
{
//Do work
}
}
To use this class, you must use the interface to access the object.
public static void Main()
{
MyFoo F = new MyFoo();
IFoo F1 = (IFoo)F;
IFoo2 F2 = (IFoo2)F;
F1.DoSomething();
F2.DoSomething();
}
The following example demonstrates using interfaces.
using System; namespace Client.Chapter_5___Building_Your_Own_Classes { class MyMainClass { static void Main(string[] args) { //The function called is based //on the type called by new B MyB = new C(); D MyD = new D(); MyB.Display(); //Calls C Display MyD.Display(); //Calls D Display } } //Creates a public interface that classes may inherit public interface A { void Display(); } class B : A { public virtual void Display() { Console.WriteLine("Class B's Display Method"); } } class C : B { public override void Display() { Console.WriteLine("Class C's Display Method"); } } class D : C { public override void Display() { Console.WriteLine("Class D's Display Method"); } } }