C# Interface

An interface contains only the declaration of the methods, properties, and events, but not the implementation. Interface makes it easy to maintain a program.

Interface Declaration and Implementation

In C#, defined interface using the interface keyword. Many different class can implement interface. When inherit from interface, then must provide implementation of its method and properties. In the below example create Iemployee interface and implement in Employee class

interface IEmployee
{
    void DisplayName(string name);
}

public class Employee : IEmployee
{
    public void DisplayName(string name
    {
        Console.WriteLine("Name : {0}", name);
    }
}

Interface Object

Interface cannot contain constructor, so you can not create object of interface using new keyword. But you can create the object of interface by storing instance of derived class.

IEmployee _employee = new Employee();

Support Multiple Inheritance

Using the interface you can able to used multiple inheritance functionality in c#. Please see below example for multiple inheritance

interface A1
{
    // …
}

interface A2
{
    // ...
}

public class Sample : A1, A2
{
    // ...
}

Explicit Implementation

You can explicit implement interface by using interface name as prefix with method name. Please see below example for explicit implementation

interface A1
{
    void Display();
}

interface A2
{
    void Display();
}

public class Demo : A1, A2
{
    public void A1.Display(){ //... } 
    public void A2.Display(){ //... }
}

Points to Remember

  • An interface only contains declarations of method, events & properties.

  • An interface does not contain constructor so, you can not create the object of interface.

  • An interface can be implement implicitly or explicitly.

  • An interface cannot change access modifier. All members are public by default.

  • Using interface you can used multiple inheritance functionality of OOPs.