What is C# interface? How to implement interface in C# code?

(Last Updated On: February 26, 2019)

Answer: C# Interface contains properties, methods, and events etc. as we have in classes. But interfaces only contains declarations and no implementation.

A class which inherit an interface is responsible to implement all the methods or items presents in the framework or user interface.

To create an interface in C#, we use “interface” keyword. For example

//interface c# code example

Note that we precede interface name with letter I only for readability purpose as a good naming convention.

e.g. Iloan, ICreditCard and IInsurence etc. as just by looking at the name, we can understand that this is an interface and it has nothing to do with compiler error.

Interface methods are public by default and we don’t need to write public modifier. If we write public, compiler will flash an error i.e. modifier public is not valid.

 

There are two types of interface in C# that is C# Implicit and Explicit interface that I have already answered for types of interfaces interview question.

 

If we derive a class from an Interface, the class will be forced to implement all methods of the Interface. If we don’t implement interface method compiler will flash an error.

For example, below PersonalLoan class is derived from Iloan interface, so, class must implement all interface method.

 

 

A class can implement multiple interfaces as explained in this technical interview question that is a scenario where only interface can be used and not abstract class in C#

C# program example using an Interface