What is Interface in C#?

When studying abstraction, we came to know it can be achieved by Abstract Class, Abstract Method, and Interface in C#. Those who have read my previous article will feel the interface in C# is very similar to the Abstract class. They are absolutely correct. The interface is similar to the Abstract class with a few differences.

Interface-in-C#

What is Interface in C#?

An Interface in C# is a contract between Interface and class that implements it. This contract says any class that implements this interface will provide the implementation for the members of the Interface. Unlike, Abstract class, Interface in C# can only contain declaration not implementation. Because all the members of the Interface are abstract and cannot have an implementation. The keyword abstract will not be used with the members of the Interfaces but the compiler will treat them as abstract members.

Just like Abstract and other special classes, Interfaces also come with some rules. Lets discuss those rules now.

Rules of Interface

  1. Interfaces are declared using the keyword Interface.
  2. An Interface cannot contain any type of variables. Neither Static nor Reference.
  3. All the members in an Interface will have only declaration and no implementation.
  4. Microsoft has made all the members in an interface are by default public.
  5. An Interface can contain properties, methods, delegates, and events etcetera.
  6. An Interface cannot be instantiated but only inherited by other classes and Interfaces. It means we cannot make an object on an Interface class.

How to Use an Interface

  1. An Interface is made to be inherited. When an Interface is inherited it is called Interface Implementation. Same Colon (:) symbols are used to implement an Interface.
  2. Once an interface is implemented in a class, all the members of the interface should be provided the implementation by the class that implemented the interface, otherwise, the class cannot be compiled.
  3. The methods of the Interface that get the implementation should have the same name and signature as Interface.

Example Program

using System;
namespace Interfaces
{
    interface IEmployee
    {
        string Name { get; set; }
        long PhoneNumber { get; set; }
        string Address { get; set; }
        void SendReport();
        void AttendMeetings();
        void CompleteGivenTasks();
        void TellPersonalDetails();
    }
    class Employee : IEmployee
    {
        public string Name { get; set; }
        public long PhoneNumber { get; set; }
        public string Address { get; set; }
        public void AttendMeetings()
        {
            Console.WriteLine("Attending Meetings");
        }
        public void CompleteGivenTasks()
        {
            Console.WriteLine("Completing Given tasks");
        }
        public void SendReport()
        {
            Console.WriteLine("Sending Reports");
        }
        public void TellPersonalDetails()
        {
            Console.WriteLine("***********************");
            Console.WriteLine("Name - {0}", Name);
            Console.WriteLine("Phone Number - {0}", PhoneNumber);
            Console.WriteLine("Address - {0}", Address);
            Console.WriteLine("***********************");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee John = new Employee
            {
                Name = "John Abraham",
                PhoneNumber = 123456789,
                Address = "New Zealand"
            };
            John.TellPersonalDetails();
            John.AttendMeetings();
            John.CompleteGivenTasks();
            John.SendReport();
            Console.ReadLine();
        }
    }
}

Program Explanation

As you can see in the program above, the IEmployee is an Interface that has the declaration of some properties and methods. There is no implementation is given in that Interface. The same symbol (:) colon is used to implement the interface that we use to inherit a class. There are 3 properties and no variables are declared in the Interface because the variables are not allowed in the interface.

There are 3 methods declared in the interface. When we implemented that interface in the class, we have created 3 methods with the same name and same signature as Interface but this time we provided the body for those methods. We provided the body because this was the responsibility of the class that implements an interface.

I believe you have understood the relationship between an interface and a class that implements it. An Interface dictates the class what should be implemented in the class without fail. If any method is available in the interface and is not implemented in the class, the entire class is useless, it will not be compiled.

Explicit Implementation of an Interface in C#

In the above example, you have seen the implicit implementation of an Interface. There is an explicit use of an Interface. But first, you need to know in what situations we use Interface explicitly.

The situation for the Explicit Implementation of Interface

Suppose we have two Interfaces E1 and E2 and in both of these Interfaces, we have a method. The name of these methods are the same and their signatures are also the same. When a class implements these two interfaces, which Interface method will get an implementation? How will the system determine which Interface method should get an implementation?

In this situation, we will use the explicit implementation of an Interface. We will explicitly tell the compiler what method of what Interface will get an implementation. We will be using type casting and rules of inheritance here. See the example below for a better understanding.

Example Program

using System;
namespace Interfaces
{
    interface E1
    {
        void Method();
    }
    interface E2
    {
        void Method();
    }
    class Employee : E1,E2
    {
        void E1.Method()
        {
            Console.WriteLine("Implementation of E1 Interface Method");
        }
        void E2.Method()
        {
            Console.WriteLine("Implementation of E2 Interface Method");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee John = new Employee();
            ((E1)John).Method();
            ((E2)John).Method();
            Console.WriteLine("*******************");
            E1 Matt = new Employee();
            Matt.Method();
            E2 Steve = new Employee();
            Steve.Method();
            Console.ReadLine();
        }
    }
}

Program Explanation

As you can see in the program above when we were giving implementation to the methods of E1 and E2. We mentioned the name of the Interface and then gave implementation.

Due to these two methods with the same name, now we have two methods with the same name in a single class. We used typecasting when calling the individual method. We typecast the object of the class to E1 and E2.

((E1)John).Method();
((E2)John).Method();

Due to typecasting, the compiler was able to understand which method should be called.

In the next line, we used the rules of inheritance. We know we can save the object of the child class in the variable of the parent class. So we made a variable of E1 and E2 interfaces and then saved the instance of child class (Employee) in that variable.

E1 Matt = new Employee();
Matt.Method();
E2 Steve = new Employee();
Steve.Method();

Due to different types of variables, the compiler was able to determine which method should be called.

Interface Chaining

An interface can implement n number of interfaces and the base interface gets the responsibility of all the members of all other interfaces. Let’s say there are four interfaces E1, E2, E3, E4, E5. E1 implements all other Interfaces then it becomes the responsibility of E1 to get the implementation of all the members of all E2, E3, E4, E5 interfaces.

Example Program

using System;
namespace Interfaces
{
    interface E1: E2,E3,E4,E5
    {
        void Show1();
    }
    interface E2
    {
        void Show2();
    }
    interface E3
    {
        void Show3();
    }
    interface E4
    {
        void Show4();
    }
    interface E5
    {
        void Show5();
    }
    class Program
    {
        class Employee : E1
        {
            public void Show1()
            {
                Console.WriteLine("Implementation of Show1 Method from E1");
            }
            public void Show2()
            {
                Console.WriteLine("Implementation of Show2 Method from E2");
            }
            public void Show3()
            {
                Console.WriteLine("Implementation of Show3 Method from E3");
            }
            public void Show4()
            {
                Console.WriteLine("Implementation of Show4 Method from E4");
            }
            public void Show5()
            {
                Console.WriteLine("Implementation of Show5 Method from E5");
            }
        }
        static void Main(string[] args)
        {
            Employee employee = new Employee();
            employee.Show1();
            employee.Show2();
            employee.Show3();
            employee.Show4();
            employee.Show5();
            Console.ReadLine();
        }
    }
}

Explanation of Program

As you can see in the above program, E1 in implementing all other E2,E3,E4,E5 and E1 gets the responsibility of all methods of Show1, Show2, Show3, Show4, Show5. E1 is implemented by Class Employee and all responsibility of E1 is passed on to the instance of Employee Class.

I hope the concept of Interfaces and their usage is clear to you by now. In case of any confusion, feel free to comment I will be glad to assist you further.

Stay Safe Stay Healthy, Take Care!

Get real time updates directly on you device, subscribe now.

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More