Dec 1, 2014

Interface in C#

An interface is template which is defined as a contract and strictly followed by inheriting class. The interface contains signature only means 'What' part of contract and deriving classes define the 'How' part of the contract.

Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.

An interface contains only the signatures of methods, properties, events or indexers. Interfaces contains only declaration of the member, default access modifier is public of declare members of Interface but you can't write with declaration of members.

Example

interface MyInterface
{
    void MyMethod();
}

class DerivedClass : MyInterface
{
    // Explicit interface member Derived: 
    void MyInterface.MyMethod()
    {
        // Method Derived.
    }

    static void Main()
    {
        // Declare an interface instance.
        MyInterface obj = new DerivedClass();

        // Call the member.
        obj.MyMethod();
    }
}