Interface in C# with Example

Interface in C# with Example
Rating: 5 - 1 Votes

Interface in C# with Example

Interface in C# with Example

Interface in C# with Example

Interface is an another important pillar of object oriented programming.  An interface only contains declaration of its members like properties, methods, delegates, and events, but not fields.  Make sure, you should not provide implementation for any of its member inside the interface.  To create an interface, we make use of interface keyword.  By common naming convention, whenever we create an interface, we put I as prefix.  It helps in quickly recognizing that we are using an interface.

All the interface members are public by default, so make sure you should not put any kind of access modifier in front of any of its member.  A class and structure both can inherit from an interface, so in this case, we must provide implementation for all of its members.

Output:

Employee Name: Albert Pinto
Press any key to continue . . .

In C#, multiple interface inheritance is allowed.  Due  to this, if your class or structure is inheriting from multiple interfaces, you must provide implementation for all the members available in those interfaces, failing to do so will result in compile time error.

Output:

Employee Name: Albert Pinto
Employee ID: 100

An interface can also inherit from another interface or multiple interfaces.  In this case, you again have to provide implementation for all the interface members available in that inheritance chain.

 Output:

Employee Name: Albert Pinto
Employee ID: 100
Employee Designation: Supervisor

The most important thing which you have to remember is that you cannot create an instance of interface like a class or a structure because interface only contains declaration, not implementation.  However, from class inheritance, we know that a base class reference variable can point to the derived class object.  Same goes in this case, if your class or structure in inheriting from an interface, you can create a reference variable of that interface and point it to the derived class or structure object.

 Output:

Employee Name: Albert