Hello Friends, in this tutorial I am going to tell you about Interface in C# with example also we will create a simple example using Interface in C#.

After completing this tutorial you will be able to understand:

  • Interfaces in C#.
  • Features of Interface.
  • How to declare an Interface.
  • How to implement an interface.
  • Why should we use an interface?
  • Difference between Abstract Class and Interface.

Introduction:

Interface in C# is like a Contract that enforces its client (Class) to follow all protocols. This contract ensures that the class will implement all methods, properties, events defined in the interface. The interface contains only the signature, not the implementation the implementation. Since C# does not support multiple inheritances, so Interface is a way to achieve multiple Inheritances in C#. The interface is used to define what to do not how to do. The “how” part is defined by the class that implement the interface.

An example of Interface:

.NET framework provides an Interface IDisposable which forces to implement Dispose() method to the class that going to implement this Interface. This method is used to dispose of the members that are no longer in use.

Real world example:

A good example of an interface that exists in the real world is a vehicle. All vehicles have some common features, however that area unit completely different enough that we have a tendency to might style associated interface that holds all the common things of a vehicle. Some vehicles have a pair of wheels, some have four wheels, though these area unit variations they need one thing in common, they are all movable, all of them have an engine, all of them have doors, however every of those things might vary. Thus we are able to write interface of a vehicle that has these properties, then we have a tendency to inherit from that interface to implement it.

The syntax for declaring Interface:

interface IMyInterface

{

Void MethodName();

}

You can see in above syntax I have declared an interface with the name IMyInterface. A good naming convention pattern for declaring interface is that prefixes all interface names with a capital “I”. Also, I have declared a method named “MethodName()” with return type void. You can use any return type in place of void.

Implement an Interface.

Class InterfaceImplementer: IMyInterface

{

static void Main()

{

InterfaceImplementer obj InterfaceImplementer=new InterfaceImplementer();

obj InterfaceImplementer.MethodName();

}

public  void MethodName()

{

Console.WriteLine(“Interface Tutorial”);

}

Interface is implemented using “:”.

Features of Interface:

  • The interface supports multiple inheritances.
  • The interface contains an only declaration, not implementation.
  • The interface does not contain Constructor.
  • We cannot declare members of the interface as private, protected, sealed and abstract.

Why should we use interface?

Since interface does not provide implementation then the question is why should we use interface?The interface provides us component based loose coupling programming. The interface provides as facilities like code reusability, scalability and maintainability because the implementation is separate. You should use an Interface in the following scenario. The interface provides a plug and plays architecture to our application.

  • You can use an Interface when you don’t know the default functionality or you don’t have shared code implementation.
  • You can use an Interface when you want to share your data as Contract for another implementer.
  • Suppose while developing an application you will get a situation like, where you have a single method with two different implementations. In such scenario, Interface is best practice. A good example of such scenario is IDbCommand has SqlCommand and OracleCommand. Both of these classes implemented IDbCommand interface in two different ways.

Difference between Abstract Class and Interface.

  • An abstract keyword is used to create an abstract class whereas interface keyword is used to create an interface.
  • An abstract class does not provide full abstraction. This means that it can have abstract as well concrete method i.e. Method with or without implementation. On the other side, Interface provides full abstraction i.e. it can only have a signature, not implementation.
  • An abstract class doesn’t provide support of multiple inheritances whereas interface provides support of multiple inheritances.
  • Abstract class allows declaration of variables whereas interface does not allow declaration of member fields.
  • We can declare a member of an Abstract class as static, abstract, sealed and virtual whereas with the interface it cannot be possible.

Interface

Let’s create an example of Interface using C# Visual Studio.

Step 1- Open Visual Studio and create a Console Application with name InterfaceDemo.

Interface

Step 2- Right click on solution explorer and create an Interface with the name IShape.

Interface

Step 3- Define an abstract method CalculateArea. Here is the code for IShape interface.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;




namespace InterfaceDemo

{

    interface IShape

    {

        void CalculateArea();

    }

}

Step 4- Right click on Solution Explorer and add a class with the name Rectangle.

Interface

Step 4-  Implement Ishape interface:

class Rectangle:IShape

    {

    }

Step 5- Now we need to implement CalculateArea method of IShape interface. You can do this by following the below snapshot.

Interface

Step 5- Click on the Implement interface “Ishape”. The complete code for Rectangle class is:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;




namespace InterfaceDemo

{

    class Rectangle:IShape

    {

        public void CalculateArea()

        {

            int iLength, iWidth,iArea;

            Console.WriteLine("Enter Length of Rectangle");

            iLength = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter Width of Rectang;e");

            iWidth = Convert.ToInt32(Console.ReadLine());

            iArea = iLength * iWidth;

            Console.WriteLine("Area of Rectangle is {0}", iArea);




        }

    }

}

Step 6 – Add a new Class with the name Triangle and implement Ishape interface.

Interface

Here is the source code for Triangle class:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;




namespace InterfaceDemo

{

    class Triangle:IShape

    {

        public void CalculateArea()

        {

            int iBaseLine, iHeight, iArea;

            Console.WriteLine("Enter BaseLine of Triangle");

            iBaseLine = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter Width of Triangle;e");

            iHeight = Convert.ToInt32(Console.ReadLine());

            iArea = iBaseLine * iHeight/2;

            Console.WriteLine("Area of Triangle is {0}", iArea);

        }

    }

}

Step 7- Now it’s time to call these two classes. Go to Program.cs file and create objects of these two classes and call the CalculateArea method like this. Here is the structure of Program.cs file.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;




namespace InterfaceDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            IShape objRectangle =new Rectangle();

            objRectangle.CalculateArea();

            IShape objTriangle = new Triangle();

            objTriangle.CalculateArea();

            Console.ReadLine();

        }

    }

}

Now run the application and test the program.

Interface

You can download the full source code from here.

You must also follow the related links.

Conclusion:

I hope this is a useful post and makes your concept more clear about Interface, how to implement an Interface and what is the difference between an Abstract class and Interface. This is also mostly asked a question during Interviews.

Thank You.

 

Leave a Comment