Interface in C# with Examples

Like a class, Interface can have methods, properties, events, and indexers as members. But the interfaces only contain the membership statement. The implementation of the interface members is given by the class that implicitly or explicitly implements the interface.

  • Interfaces specify what a class should do, not how.
  • Interfaces cannot have private members.
  • By default, all members of the interface are public and abstract.
  • The interface is always defined by the keyword "interface".
  • The interface cannot contain fields because they represent a specific implementation of data.
  • Multiple inheritances are possible using interfaces, but not classes.

Syntax:

interface  <name>
{
      //  declaration
}

Example of interface implementation:

interface Result
{
    void Show();
}
class newclass : Result
{
    public void Show()
    {
        Console.WriteLine("Hello word");
    }
    public static void Main(String[] args)
    {
        newclass newclass = new newclass(); 
        newclass.Show();
    }
}

Output:

Hello word

Advantage of the interface:

  • It is used to achieve loose coupling.
  • Achieve the total abstraction
  • To perform component-based programming To achieve more heritage and abstraction.
  • Interfaces add plug-and-play architecture to applications.