Interfaces in C#

Interfaces:

  • Interfaces are contracts that defines the signature of functionality.
  • Interfaces are useful when creating hierarchy of unrelated classes.

Interface Example:


public interface InterfaceA
{
void Display();
}

public class DerivedA : InterfaceA
{
  public void Display()
 {
    Console.WriteLine("Display Method DerivedA");
 }

 void InterfaceA.Display()
 {
   Console.WriteLine("Display Method InterfaceA DerivedA");
 }
}

There is one Display method and other Display method is explicitly implemented. This works fine and does not throw error.

Two interfaces with same method name:

public interface InterfaceA
{
void Display();
}

public interface InterfaceB
{
void Display();
}

In such case we need to explicitly define the method

public class DerivedA : InterfaceA, InterfaceB
{
public void Display()
{
Console.WriteLine("Display Method DerivedA");
}

void InterfaceA.Display()
{
  Console.WriteLine("Display Method InterfaceA DerivedA");
}

void InterfaceB.Display()
{
  Console.WriteLine("Display Method InterfaceB DerivedA");
}
}

Main Method:

static void Main(string[] args)
{

InterfaceA AObj = new DerivedA();
AObj.Display();

InterfaceB BObj = new DerivedA();
BObj.Display();

Console.ReadLine();
}

Result:

Display Method InterfaceA DerivedA
Display Method InterfaceB DerivedA

Modifying interface/Adding new method to interface:

Ideally interface should not change after it is used. But if there is situation where we need to add new method to interface as example below.  One of the way is mentioned below:

Let say there is interfaceA and we want add new method Print()

public interface InterfaceA
{
void Display();
}

InterfaceA is being used. User wants to add new method to it.

Create new interface with method to be implemented and inherit it from original interface.

public interface InterfaceB : InterfaceA
{
void Print();
}

Now use newly created interface were needed. Don’t change other class implementation.

When to use interfaces:

  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface.
  • If you are designing small, concise bits of functionality, use interfaces.
  • Interfaces cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.