Write code for interface implementation in C#

Answer includes the concept for interface implementation in C# with example and code example of multiple interface implementation.

Answer: C# Interface inheritance or implementation is a simple concept object oriented programming. Let’s understand in a simple word.  We create an interface having one or more unimplemented methods in it. A class implements this interface, meaning, the class implements all methods available in the interface.

Note that a class should implement all methods from interface or else compiler will flash an error.

Here is an example program, in which class Aeroplane will inherit an interface and will implement an interface called IFlyable. Meaning, it will implement the method fly() present in IFlyable interface.

Example of single interface implementation in C#

interface IFlyable
{
     void fly();
}

//Aeroplane class will implement interface
class Aeroplane : IFlyable
{
    //Implement method of interface
    public void fly(){
        Console.WriteLine("Aeroplane flying");
    }
   
}


//TEST PROGRAM
class Program
{
    static void Main(string[] args)
    {
        Aeroplane a = new Aeroplane();
        a.fly();
    }
}

A class can inherit or implement multiple interfaces in C# programming. Note that multiple class inheritance is not supported in C# programming. But, multiple interfaces can be inherited and implemented.

Example of Multiple interface implementation in C#:

In this multiple interface implementation example, we will be inheriting two interfaces and implements methods from both interfaces into class Bird.

interface IFlyable
{
     void fly();
}
interface IEatable
{
    void eat();
}

//Bird class will implement interface
class Bird : IFlyable,IEatable
{

    //Implement method of interface
    public void fly(){
        Console.WriteLine("Bird flying");
    }
    public void eat()
    {
        Console.WriteLine("Bird eats");
    }
}


//TEST PROGRAM
class Program
{
    static void Main(string[] args)
    {
        Bird b = new Bird();
        b.eat();
        b.fly();
    }
}


Read another interview question – Tell example scenario, where C# interface is indispensable.

Related Posts