C#

C# Interface

C# Interface defines a group of related functionality. An interface defines only the definition of the functionality. All classes and structures which inherit from interface must implement the functionality defined in an interface.

We can not create an instance of interface. In the interface declaration variable, we can only store the instance of the object that implements the interface.

An interface contains only methods, properties, events and indexers.

Syntax of C# Interface

Below is the syntax of interface and its usage:

interface IContract
{
    event EventHandler MyEvent;
    string Property1 { get; set; }
    string this[int i] { get; }
    void DoWork();
}

public class ContractImpl : IContract
{
    private string property1;

    public event EventHandler MyEvent;

    public string Property1
    {
        get
        {
            return property1;
        }
        set
        {
            property1 = value;
        }
    }

    public string this[int i]
    {
        get
        {
            switch (i)
            {
                case 1: return "First";
                case 2: return "Second";
                default: return "None";
            }
        }
    }

    public void DoWork()
    {
        // do work code
    }
}

class Program
{
    static void Main(string[] args)
    {
        IContract cont = new ContractImpl();
        cont.Property1 = "Hello";
        cont.MyEvent += cont_MyEvent;
        string value = cont[1];
        cont.DoWork();
    }

    static void cont_MyEvent(object sender, EventArgs e)
    {
            
    }
}

In the above code, we have declared an interface IContract and a class ContractImpl which implements the interface. In the Main method, we declare a variable of interface type ‘cont’ and initialize with the ContractImpl instance. By using interface variable, we can only access the members which are specify in the interface.

Interface access modifiers

An interface can only have two access modifiers. These are

  1. public
  2. internal

You can declare an interface that has private or protected modifier. Below is the example of two interfaces one is public and other one is internal.

public interface IContract {}

internal interface IContact2 { }

Interface members access modifiers

We cannot declare any access modifiers with interface members. All the interface members are implicitly public.

In the below example, we have declared an access modifier with the interface members.

public interface IContract
{
    public int Member1 { get; set; }        //This interface will not compile
}

C# compiler will issue an error “The modifiers ‘public’ is not valid for this item.

Interface Multiple Inheritance

An interface can inherit from another interface. We can create an entire hierarchy of interfaces inheriting from each other.

public interface IContract1
{
    void Method1();
}

public interface IContract2 : IContract1
{
    void Method2();
}

public interface IContract3 : IContract2
{
    void Method3();
}

public interface IContract4 : IContract2
{
    void Method4();
}

An interface can inherit from one or more interfaces. You can provide a comma-separated list after the inheritance (:).


public interface IContract5: IContract1, IContract2, IContract3
{
    void Method5();
}

IContract5 is inherit from IContract1, IContract2, and IContract3. We still don’t need to implement members of the base interfaces. A class which implements IContract5 has to implement all the members of IContract1, IContract2, and IContract3.

Implementing Interfaces

We can implement interfaces in two ways:

  1. Implicit Implementation (default)
  2. Explicit Implementation

Implicit Implementation

In Implicit implementation, all the inherit members of an interface must be public access modifier. Implicit implementation is the default and most preferred way to implement interfaces.

Below is the example of implicit implementation:

public interface IControl
{
    void PaintUI();
}

public class Label : IControl
{
    public void PaintUI()
    {
        //Paint UI code
    }
}

When we create the instance of Label class, we can access the PaintUI() method from that. Below is the example:

class Program
{
    static void Main(string[] args)
    {
        Label label = new Label();
        label.PaintUI();            // An label variable can access the PaintUI() method
    }
}

Explicit Implementation

In this implementation, all the implemented members are private in the implementing class. Below is the syntax of using explicit implementation:

public interface IControl
{
    void PaintUI();
}

public class Label : IControl
{
    void IControl.PaintUI()
    {
        throw new NotImplementedException();
    }
}

In the above code, we have not used any access modifier with the PaintUI() method. We must use the interface name before the method name IControl.PaintUI(). Now, when we create an instance of Label class, we cannot access the PaintUI() method. PaintUI() is only available when we create an instance of IControl like shown below:

static void Main(string[] args)
{
    Label label = new Label();
    // This statement will not compile. An label variable can not access the PaintUI() method
    label.PaintUI();            

    IControl control = new Label();
    control.PaintUI();          // control varaible can access the PaintUI() method
}

Explicit implementation is useful when we have to implement multiple interfaces with the same method names.

Generic Interfaces

Generic allows us create a class/interface that work with data-type which we don’t know at writing the structure of the class/interface. We specify the actual data-type when the class is instantiated.

Below is the syntax of generic interfaces.

public interface ICRUD<T>
{
    T Get();
    List<T> GetAll();
    void Insert(T parameter);
    void Update(T parameter);
    void Delete(T parameter);
}

public class Employee : ICRUD<Employee>
{
    public Employee Get()
    {
        //code to get single employee
    }

    public List<Employee> GetAll()
    {
        //code to get all employees
    }

    public void Insert(Employee parameter)
    {
        //code to insert employee
    }

    public void Update(Employee parameter)
    {
        //code to update employee
    }

    public void Delete(Employee parameter)
    {
        //code to delete employee
    }
}

Final words

  1. An interface is a group of related functionality.
  2. Interface contains only the signatures of functionality. An interface can not contain any implementation.
  3. We can not create an instance of the interface.
  4. An interface contains only methods, properties, indexers and events.
  5. An inteface can inherit from multiple interfaces.
  6. A class can implement multiple interfaces.