Interface in C#

Interface in C# with Examples

In this article, I am going to discuss one of the most important concepts i.e. Interface in C# with Examples. Please read our previous article where we discussed Abstract Classes and Abstract Methods in C# with Examples. At the end of this article, I am sure, you will understand what is Interface, why we need an interface, and how to use an interface in C# with Examples.

What is an Interface in C#?

The Interface in C# is a fully un-implemented class used for declaring a set of operations/methods of an object. So, we can define an interface as a pure abstract class which allows us to define only abstract methods. The abstract method means a method without a body or implementation.

It is used to achieve multiple inheritances which can’t be achieved by class. It is used to achieve full abstraction because it cannot have a method body.

Till now we are learning classes. So, what is a class? A class is a user-defined data type. Then what is an interface? An interface is also a user-defined data type. Then what is the difference between them? Let us understand this first.

Differences between Class, Abstract Class, and Interface in C#:

A class can contain only the methods which contain the method body. Do we have a method without the body? Yes, we have methods without a body and that is called abstract methods. So, simply we can say class contains a method with a method body or you can say non-abstract methods. Abstract class contains both abstract and non-abstract methods and interface contains only abstract methods.

  1. Class: Contains only the Non-Abstract Methods (Methods with Method Body).
  2. Abstract Class: Contains both Non-Abstract Methods (Methods with Method Body) and Abstract Methods (Methods without Method Body).
  3. Interface: Contain only Abstract Methods (Methods without Method Body).

What are abstract methods, why do we need abstract methods, and how do implement abstract methods we have already discussed this in our Abstract Classes and Abstract Methods in C# article.

Note: Every abstract method of an interface should be implemented by the child class of the interface without fail (Mandatory).

In Inheritance, we already learned that a class inherits from another class, and the child class consumes the members of the Parent class. Please observe the following diagram. Here, we have class A with a set of members and class B is inheriting from class A. And there is a relationship called Parent/Child relation between them. And once the Parent/Child relationship is established, then the members of class A can be consumed under class B. So, this is what we learned in Inheritance.

Interface in C#

Now, just like a class is having another class as a Parent, a class can also have an Interface as a Parent. And if a class has an interface as a Parent, the class is responsible for providing the implementation for all the abstract methods of the interface. For a better understanding, please have a look at the below diagram.

Interface in C#

Simply speaking, the Parent Interface imposes restrictions on the Child Classes. What restrictions? The restrictions are to implement each and every method of the interface under the child class.

Generally, a class inherits from another class to consume members of its Parent. On the other hand, if a class is inheriting from an interface, it is to implement the members of its Parent (Interface), not for consumption.

Note: A class can inherit from a class and interface(s) at a time.

How to Define an Interface in C#?

The way we define a class, in the same way, we need to define an interface in C#. In a class declaration, we need to use the class keyword whereas in an interface declaration we need to use the interface keyword. Moreover, in an interface, we can only declare abstract members. For a better understanding, please have look at the below diagram.

How to Define an Interface in C#?

For a better understanding please have a look at the below example. Here, we have created one interface with the name ITestInterface by using the interface keyword.

interface ITestInterface
{
    //Abstract Member Declarations
}
How to Define Abstract Methods in an Interface in C#?

In a class (i.e. Abstract Class), we generally use the abstract keyword to define abstract methods as follows.
public abstract void Add(int num1, int num2);

If you want to write the above abstract method in an interface, then you don’t require public and abstract keywords in the method signature as follows:
void Add(int num1, int num2);

While working with Interface we need to remember some Rules. Let us discuss those rules one by one with Examples.

Point1: The first point that you need to remember is the default scope for the members of an interface is public whereas it is private in the case of a class.

Point2: The second point that you need to remember is by default every member of an interface is abstract, so we don’t require to use the abstract modifier on it again just like we do in the case of an abstract class. For a better understanding, please have a look at the below example. By default, the Add method is going to be public and abstract.

interface ITestInterface
{
    //By default, the following method is public and abstract
    void Add(int num1, int num2);
}

Point3: The third point that you need to remember is we cannot declare fields/variables, constructors, and destructors in an interface in C#.

Please have a look at the below code. Here, we are trying to declare a variable and as soon as we declare we get one compile-time error i.e. Interfaces cannot contain fields as shown in the below image.

How to Define Abstract Methods in an Interface in C#?

What are the Members we can and can’t define in an interface in C#?

An interface can contain

  1. Abstract methods
  2. Properties
  3. Indexes
  4. Events

An interface cannot contain

  1. Non-abstract functions
  2. Data fields
  3. Constructors
  4. Destructors

Point4: The fourth point that you need to remember is if require an interface can inherit from another interface in C# just like a class inherits from another class.

For a better understanding, please have a look at the below code. Here, we have two interfaces i.e. Interface1 and Interface2. Interface2 is inherited from Interface1 and now interface2 has two abstract methods i.e. Add (from interface 1) and Sub.

What are the Members we can and can’t define in an interface in C#?

Now, the Child class who is inheriting from Interface1 has to implement one method i.e. Add and the child class who is inheriting from Interface2 has to implement two methods i.e. Add, and Sub.

Now, you may have one question why do we need two separate interfaces, why not one? Yes, you can use one interface and define all the methods as long as they are related to one task. If you put not related methods in a single interface then it is against the SOLID – Interface Segregation Principle. If you want to learn the SOLID – Interface Segregation Principle please click here.

Point5: The fifth point that you need to remember is every member of an interface should be implemented under the child class without fail (mandatory), but while implementing we don’t require to use the override modifier just like we have done in the case of an abstract class.

For a better understanding, please have a look at the following code. Here, we have two interfaces and two implementation classes. Interface2 is inherited from Inteface1 and hence it has two abstract methods. ImplementationClass1 inherits from Interface1 and hence implements the Add method only. ImplementationClass2 inherits from Interface1 and Interface2 inherits from Interface1 and hence this class needs to implement both the abstract methods. That is what you can see in the below code.

interface ITestInterface1
{
    void Add(int num1, int num2);
}
interface ITestInterface2 : ITestInterface1
{
    void Sub(int num1, int num2);
}

public class ImplementationClass1 : ITestInterface1
{
    //Implement only the Add method
    public void Add(int num1, int num2)
    {
        Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");
    }
}

public class ImplementationClass2 : ITestInterface2
{
    //Implement Both Add and Sub method
    public void Add(int num1, int num2)
    {
        Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");
    }

    public void Sub(int num1, int num2)
    {
        Console.WriteLine($"Divison of {num1} and {num2} is {num1 - num2}");
    }
}

In the above example, you can see that while implementing the method we are using the public modifier and this is required. If you don’t use public, then it will treat the method as private and you will get a compiler error ‘ImplementationClass1’ does not implement interface member ‘ITestInterface1.Add(int, int)’. ‘ImplementationClass1.Add(int, int)’ cannot implement an interface member because it is not public. as shown in the below image.

Interface in C# with Examples

Example to Understand Interface in C#:

Whatever we discussed as of now, we have put all these things in the below example. Please go through the comment lines.

using System;
namespace AbstractClassMethods
{
    class Program
    {
        static void Main()
        {
            ImplementationClass1 obj1 = new ImplementationClass1();
            //Using obj1 we can only call Add method
            obj1.Add(10, 20);
            //We cannot call Sun method
            //obj1.Sub(100, 20);

            ImplementationClass2 obj2 = new ImplementationClass2();
            //Using obj2 we can call both Add and Sub method
            obj2.Add(10, 20);
            obj2.Sub(100, 20);

            Console.ReadKey();
        }
    }
    
    interface ITestInterface1
    {
        void Add(int num1, int num2);
    }
    interface ITestInterface2 : ITestInterface1
    {
        void Sub(int num1, int num2);
    }

    public class ImplementationClass1 : ITestInterface1
    {
        //Implement only the Add method
        public void Add(int num1, int num2)
        {
            Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");
        }
    }

    public class ImplementationClass2 : ITestInterface2
    {
        //Implement Both Add and Sub method
        public void Add(int num1, int num2)
        {
            Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");
        }

        public void Sub(int num1, int num2)
        {
            Console.WriteLine($"Divison of {num1} and {num2} is {num1 - num2}");
        }
    }
}
Output:

Example to Understand Interface in C#

Point6: We cannot create an instance of an interface, but we can create a reference of an interface. The interface reference is going to hold the child class instance. Using the interface reference, we can only invoke the methods which are declared in the interface.

For a better understanding, please have a look at the below example. In the below example, ITestInterface1 declared one abstract method i.e. Add. This interface is then implemented by the ImplementationClass and this class provides the implementation for the Add interface method. Again, in this class, we defined a new method i.e.Sub. Next, inside the Main method, we are creating a reference of the interface which is pointing to the child class instance. And using this reference we can only invoke the Add method and we cannot invoke the Sub method. This is because the Add method signature is there inside the interface but the Sub method signature is not there in the interface.

Example to Understand Interface Reference in C#:
using System;
namespace AbstractClassMethods
{
    class Program
    {
        static void Main()
        {
            //Creating Reference of an Interface point to the 
            //child class instance
            ITestInterface1 obj = new ImplementationClass();

            //Add method signature declared in ITestInterface1, so we can
            //Invoke the Add method
            obj.Add(10, 20);

            //Sub method signature is not declared in ITestInterface1, 
            //so, we cannot Invoke the Sub method
            //obj.Sub(100, 20);
            
            Console.ReadKey();
        }
    }
    
    interface ITestInterface1
    {
        void Add(int num1, int num2);
    }
    
    public class ImplementationClass : ITestInterface1
    {
        //Interface Method Implementation
        public void Add(int num1, int num2)
        {
            Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");
        }

        //This method purely belongs to ImplementationClass
        public void Sub(int num1, int num2)
        {
            Console.WriteLine($"Divison of {num1} and {num2} is {num1 - num2}");
        }
    }
}
Explicit Interface Implementation in C#

When each interface method is implemented separately under the child class by providing the method name along with the interface name then it is called Explicit Interface Implementation. But in this case, while calling the method we should compulsorily use the interface reference that is created using the object of a class or type cast the object to the appropriate interface type. 

You can also implement an interface in another way without using the public access modifier. In this case, we need to specify the interface name before the method name using the dot operator as shown in the below code. This is called Explicit Implementation of Interface Methods.

Explicit Interface Implementation in C#

As you can see in the above code, the Add method is implemented using public access specifier and the Sub is implemented using the interface name. The Sub method belongs to Interface2 and hence we prefix the Sub method with Interface2 followed by the dot operator. Here, if you want to implement Add method in an explicit manner then you need to prefix the Add method with Interface1 as the Add method belongs to Interface1.

In this case when we use the Interface name while implementing the interface method then we don’t require to use the public access specifier anymore. The reason is that it is very clear that interface members are public and hence we don’t require to use the public access specifier. So, these are the two ways of implementing interface members in C#.

Now, if the method is implemented using the public access specifier, then you can create the object and call them directly. But if the method is implemented using the interface name, then while calling the method we need to typecast the object to the interface type or you can create an interface reference and call the method. So, in our case, we call Add method directly using obj1 but while calling the Sub method we need to typecase the obj1 to Interface2 type as this is an instance of ImplementationClass or you can call directly using reference variable obj2 as shown in the below image.

Differences between Class, Abstract Class, and Interface in C#

Explicit Interface Implementation Example in C#
using System;
namespace AbstractClassMethods
{
    class Program
    {
        static void Main()
        {
            ImplementationClass obj1 = new ImplementationClass();
            //Using obj1 we can call the Add method directly because
            //It is implemented using public access specifier
            obj1.Add(10, 20);

            //We need to typecast obj1 to ITestInterface1 to call the Sub
            //method because Sub method is implemented using Interface name
            ((ITestInterface1)obj1).Sub(100, 20);

            //We can call the method directly using the interface reference
            //Typecasting is not required in this case
            ITestInterface1 obj2 = new ImplementationClass();
            obj2.Add(200, 50);
            obj2.Sub(200, 50);

            Console.ReadKey();
        }
    }
    
    interface ITestInterface1
    {
        void Add(int num1, int num2);
        void Sub(int num1, int num2);
    }
    
    public class ImplementationClass : ITestInterface1
    {
        //Interface Method Implementation
        public void Add(int num1, int num2)
        {
            Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");
        }

        //This method purely belongs to ImplementationClass
        void ITestInterface1.Sub(int num1, int num2)
        {
            Console.WriteLine($"Divison of {num1} and {num2} is {num1 - num2}");
        }
    }
}
Output:

Explicit Interface Implementation Example in C#

In the next article, I am going to discuss Interface Interview Questions and Answers in C# with Examples. Here, in this article, I try to explain the Interface in C# with Examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this Interface in C# with the Examples article.

5 thoughts on “Interface in C#”

  1. blank

    Hello, when i run this prog, by step by step, the prog work fine. But, for better understanding, I was disappointed that it does not pass inside the interface… Thank you for this tutorial, I will continue the tutorial.

Leave a Reply

Your email address will not be published.