C#-Interface with Example

C# – Interface with example

interface is same like class but only difference is class can contain both declarations and implementation of methods,events and properties but interface will contain only the declarations of methods that a class or struct can be implement.

c# will not support multiple inheritance but that can be achieved by using interface. In addition, a structure in c# cannot be inherited from another structure or class but that can be inherited by using interfaces

In c#, we can define an interface by using interface keyword. Following is the example of defining an interface.

    interface IDetail
    {
       void GetDetails();
    }

In above code snippet, we defined an interface (IDetail) using interface keyword with GetDetails method signature. Now, the IDetail interface can be implemented by any class or struct by providing a definition for GetDetails method.

To implement an interface in a class or structure the following syntax will be used.

class Detail: IDetail
{
    void InserDetails()
    {
       // Method Implementation
    }
}

If you observe code snippet, we inherited an interface (IDetail) in a class (Detail) and implemented a defined interface method in class

C# Multiple Inheritance using Interface

Below is the example of implementing a multiple inheritance using interfaces in c# programming language.

using System;
namespace OppsConcept
{
    interface IName
    {
        void GetName(string a);
    }

    interface ICountry
    {
        void GetCountry(string a);
    }

    interface IAge
    {
        void GetAge(int a);
    }

    class User : IName, ICountry, IAge
    {
        public void GetName(string a)
        {
            Console.WriteLine("Name: {0}", a);
        }

        public void GetCountry(string a)
        {
            Console.WriteLine("Country: {0}", a);
        }

        public void GetAge(int a)
        {
           Console.WriteLine("Age: {0}", a);
        }
    }

When we execute above c# program, we will get the result like as shown below.

C# - Interface with example
Explicit Interface Implementation :

Explicit implementation is useful when class is implementing multiple interface thereby it is more readable and eliminates the confusion. It is also useful if interfaces have same method name coincidently.

Note : Do not use public modifier with an explicit implementation. It will give compile time error.

You can implement interface explicitly by prefixing interface name with all the members of an interface, as shown below:

using System;
namespace OppsConcept
{ 
    interface IPen
    {
        string Color { get; set; }
        bool Open();
        bool Close();
        void Write(string text);
    }

    class Cello : IPen
    {
        string IPen.Color { get; set; }

        private bool isOpen = false;

        bool IPen.Close()
        {
            isOpen = false;
            Console.WriteLine("Cello closed for writing!");

            return isOpen;
        }

        bool IPen.Open()
        {
            isOpen = true;
            Console.WriteLine("Cello open for writing!");

            return isOpen;
        }

        void IPen.Write(string text)
        {
            if (isOpen)
                Console.WriteLine("Cello: " + text);
        }
    }

     class Program
     {
        static void Main(string[] args)
        {
            IPen mypen = new Cello();
            mypen.Open();
            mypen.Write("Hello Frinds!");
            mypen.Close();
        }
     }
 }

In the above example of explicit implementation, notice that it cannot use access modifier ‘public’ explicitly. C# will give an error if you use ‘public’ modifier when implementing interface explicitly.

There can be multiple classes or structs that implements the same interface. Consider the following example.

class Notebook: IPen
{
    public string Color { get; set; }        
    private bool canWrite = false;        
    public bool Close()
    {
        canWrite = false;
        Console.WriteLine("Notebook is closed now!");
        return canWrite;
    }

    public bool Open()
    {
        canWrite = true;
        Console.WriteLine("Notebook is open now!");            
        return canWrite;
    }

    public void Write(string text)
    {
        if(canWrite)
            Console.WriteLine("Notebook: " + text);
    }
}

As you can see, the Notebook class implements the IPen class. It implements the same functionalities declared in IPen class but in a different way than Cello class. (prints different messages in Open(), Close() and Write() methods.) Thus, multiple classes or Structs can implement the same interface which performs the same action but differently.

The same variable can be used to instantiate all the classes which implemented IPen interface.

IPen objPen = new Cello();
objPen = new Parker(); 

The following point’s to be remember when implement an interface

  1. An interface only contains declarations of method, properties, indexers, and events.
  2. An interface can be implement implicitly or explicitly by a class or struct.
  3. By default, the members of interface are public and we are not allowed to include any other access modifiers
  4. Do not include ‘public’ in an interface as all the members are public by default. C# will give compile-time error if used ‘public‘.
  5. The class or struct that implements an interface must provide an implementation for all the members that are specified in the interface definition.
  6. The class or struct can implement multiple interfaces.

Difference between Abstract Class and Interface

Abstract Class Interface
 abstract classes cannot be instantiated the abstract classes cannot be instantiated interface cannot be instantiated directly, but it can be instantiated by a class or struct that implements an interface
The members of abstract class can contain different access modifiers. By default, all the members of interface are public and we are not allowed to include any other access modifiers.
class can inherit only one abstract class class can inherit multiple interfaces

Also Learn More Tutorial :

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *