What is an Interface in C#


share this interview article on:

What is an Interface in C# ?

An Interface is similar to an Abstract class but has no implementation. 

Cannot be instantiated i.e. object cannot be created using the new keyword.

The only thing it contains are declarations of events,  methods and properties. The reason interfaces only provide declarations is because they are inherited by classes and structs, which must provide an implementation for each interface member declared.

 

Declaration of Interface:

interface keyword used with declaration of interface.

interface IMyInterface
{
    void MethodToImplement();
}

IMyInterface is the name of interface and a single method MethodToImplement() is declared with no parameters and no implementation.

 

Sample example of using an Interface:

class InterfaceImplementer : IMyInterface
{
    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
    }

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }
}

The InterfaceImplementer class implements IMyInterface

Indicating that a classinherits an interface is the same as inheriting a class.

 the following syntax is used that a class inherits an interface.

class InterfaceImplementer : IMyInterface

 

Now that this class inherits the IMyInterface interface, it must implement its members. It does this by implementing theMethodToImplement() method.

Notice that this method implementation has the exact same signature, parameters and method name, as defined in the IMyInterface interface.

Any difference between the method signature in the interface and the method signature in the implementing class or struct will cause a compiler error.

Additionally, a class or struct that inherits an interface must include all interface members; You will receive a compiler error if you don’t implement all interface members.



Related Interview Questions

ADS

Tags: