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

Answer: In C#, an interface contains properties, methods, and events etc., similar like we have in a class. But, an  interfaces only contains declarations of methods and no implementation.

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

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

//interface c# code example

interface Iloan
{

void getInfo();

}

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 i.e. implicit and explicit in C# language.

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.

class PersonalLoan : Iloan
{
    //interface implementation
    public void getInfo()
    {
        Console.WriteLine("Get Personal Loan Info");
    }   
    public void processLoan(){
        Console.WriteLine("Process loan");
    }
}

A class can implement multiple interfaces as explained in this technical interview question:  a scenario where only interface can be used not an abstract class in C# programs.

C# program example using an Interface

interface Iloan
{
   void getInfo();
}

class PersonalLoan : Iloan
{
    //interface implementation
    public void getInfo()
    {
        Console.WriteLine("Get Personal Loan Info");
    }   
    public void processLoan(){
        Console.WriteLine("Process loan");
    }
}

//Test
class Program
{
    static void Main(string[] args)
    {
        PersonalLoan loan = new PersonalLoan();
        loan.getInfo();
        loan.processLoan(); 
    }
}

Related Posts