C# Interface

0
1376

Interfaces are the types in C# like classes but it contains only abstract members in it.

It contains empty definitions of methods, functions, events, and indexers. When class is implemented from the interface, it must provide the implementation for all members in the interface.

After defining the interface, it can be implemented by any number of classes. The interface defines what to be done but not how the actual action is defined in classes that implement the interface.

Interfaces in C#

Defining interface:
The general syntax for defining interface is as below:

interface <Interface_Name>
{
    //Abstract members
}

In C#, interface keyword is used to define an interface followed by interface name. Interface body is enclosed within curly braces. All members of the interface are implicitly public therefore no explicit access modifier is allowed to them.

Although it is not mandatory to use prefix ‘I’ in the interface it is good programming practice to use prefix ‘I’ in interface name, so that one can differentiate between class and interface just by looking at the name.

Some points to remember in defining the interface:

1.The interface cannot contain data members means we cannot declare any variable inside interface.

2.All interface members are implicitly abstract and public therefore there is no need of abstract keyword to declare abstract members.

3.They cannot contain constructors, destructors and operator methods.

4.Interface members cannot be declared as static.

Implementing Interface:

After defining interface one or more classes can implement it. To implement an interface in a class, the name of the interface is specified with colon just like inheritance. The general syntax for implementing the interface is as below:

class<Class_Name>:<Interface_Name>
{
   //Body of class
}

Here Class_Name is the name of the class which is going to implement interface and Interface_Name is the name of the interface.

If a class implements the interface then it must implement all members of the interface as all members are abstract.

The methods which are implemented from the interface must be declared as public because these methods are implicitly public in the interface.

We know that C# does not support multiple inheritances through classes that mean we cannot inherit properties of more than one base class in derived class. But it supports multiple inheritances through the interface.

Recommended Post   C# Tutorial

A class can implement more than one interface. The general syntax to implement multiple interfaces is as below:

class<Class_Name>:<Interface_Name1>,<Interface_Name2>
{
   //Body of class
}

To implement multiple interfaces, comma separated interface names are given after class name. When a class implements more than one interface, it must implement all members of all interfaces.

We also can inherit a base class and implement interfaces in a class as below:

class<Class_Name>:<Base_Class>,<Interface_Name1>,<Interface_Name2>
{
   //Body of class
}

In this situation, the base class name should be first in comma separated list.

Example:

using System; 
namespace InterfaceDemo 
{ 
   interface IArithmeticOperation 
   { 
      int ShowResult(); 
   } 
   class AdditionDemo : IArithmeticOperation 
   { 
      public int number_1; 
      public int number_2; 
      public int ShowResult() 
      { 
         return number_1 + number_2; 
      } 
   } 
   class MultiplicationDemo : IArithmeticOperation 
   { 
      public int number_1; 
      public int number_2; 
      public int ShowResult() 
      { 
         return number_1 * number_2; 
      } 
   } 
   class Program 
   { 
      static void Main(string[] args) 
      { 
         AdditionDemo additionDemo = new AdditionDemo(); 
         additionDemo.number_1 = 10; 
         additionDemo.number_2 = 20;
         Console.WriteLine("Result of Addition is: " + additionDemo.ShowResult());
         MultiplicationDemo multiplicationDemo = new MultiplicationDemo();
         multiplicationDemo.number_1 = 10;
         multiplicationDemo.number_2 = 20;
         Console.WriteLine("Result of Multiplication is: " + multiplicationDemo.ShowResult()); 
         Console.ReadLine(); 
      } 
   } 
}

The output of program is

Result of Addition is: 30
Result of Multiplication is: 200

In above program, we define interface IArithmeticOperation and declare ShowResult() method in it. Here ShowResult() method is implicitly public and abstract, so we don’t use abstract keyword and any other access modifier.

Here we enforce the classes which implement the IArithmeticOperation interface must provide the result of an operation in ShowResult() method.

In above cases addition operation and MultiplicationOperation classes implement IArithmeticOperation, so it is mandatory for these two classes to implement ShowResult() method.

Using Interface References:

As all members of interfaces are abstract so we cannot create any object of interface. But we can create a reference variable of interfaces which refers to the object that implements its interface.

Using this reference variable one can access derived class’s methods which are implemented from the interface. Here the derived class’s data members and pure methods which are not implemented from the interface are not accessible to the interface reference variable.

Suppose we change the definition of class AdditionOperation in above program and add one method Display() in it as below:

class AdditionDemo : IArithmeticOperation
{
   public int number_1;
   public int number_2;
   public int ShowResult()
   {
      return number_1 + number_2;
   }
   public void Display()
   {
      Console.WriteLine("Executing Display method of AdditionDemo.");
   }
}

Now in Main() method we create the reference variable of interface IArithmeticOperation and create a new object of class AdditionDemo and assign it to the reference variable of the interface. The changed form of the main method is as below:

static void Main(string[] args)
{
   IArithmeticOperation additionDemo = new AdditionDemo();
   // additionDemo.number_1 = 10; Not Accessible
   //additionDemo.number_2 = 20; Not Accessible
   Console.WriteLine("Result of Addition is: " + additionDemo.ShowResult());
   //additionDemo.Display(); Not Accessible
   Console.ReadLine();
}

Here addition demo is reference variable of type IArithmeticOperation which refers to the object of class AdditionDemo.

Recommended Post   Access Modifiers in C#

So it is not possible to access variables number_1, number_2 and Display() method of this class using this variable but method ShowResult() is accessible as it is implemented from the interface.

Explicit implementation:

While implementing members of the interface in derived classes, one can fully qualify members name with the interface this is known as explicit implementation.

If we change the implementation of ShowResult() method in AdditionDemo class of above program and use interface name with this method then the class definition looks like below:

class AdditionDemo : IArithmeticOperation
{
   public int number_1;
   public int number_2;
   int IArithmeticOperation .ShowResult()
   {
      return number_1 + number_2;
   }
}

Here we remove public access modifier of ShowResult() method this is because in explicit implementation we must use the default access modifier. Another point in explicit implementation is we must use interface reference to access these members.

While implementing more than one interface in a class there is a possibility that two or more interfaces have the same method and creates an ambiguity of methods.

This ambiguity does not give an error but there may be a case where you want to provide interface specific different implementations for the same method, this can be achieved by explicitly implementing the method with the interface name.

Below example demonstrate interface ambiguity:

Example:

using System;
namespace InterfaceAmbiguity
{
   interface Interface1
   {
      void Show();
   }
   interface Interface2
   {
      void Show();
   }
   class ABC : Interface1, Interface2
   {
      public void Add(int x, int y)
      {
         Console.WriteLine(x + y);
      }
      public void Mul(int x, int y)
      {
         Console.WriteLine(x * y);
      }
      void Interface1.Show()
      {
         Console.WriteLine("Interface 1 Show() mehtod implemented.");
      }
      void Interface2.Show()
      {
         Console.WriteLine("Interface 2 Show() method implemented.");
      }
   }
   class Program
   {
      static void Main(string[] args)
      {
         ABC abc = new ABC();
         Interface1 I1 = abc;
         I1.Show();
         Interface2 I2 = abc;
         I2.Show();
         Console.ReadLine();
      }
   }
}

The output of program is

Interface 1 Show() mehtod implemented.
Interface 2 Show() method implemented.

In above program, class ABC implements interfaces Interface1 and Interface2. In these two interfaces, there is Show() common. In class ABC we want to provide two different versions of this method.

Recommended Post   C# Classes & Objects 

So we explicitly implement this method two times with interface name. In Main() method, as Show() method is explicitly implemented with interface names, it is not accessible to a reference variable of type ABC. So we create reference variable I1 and I2 respectively of Interface1 and Interface2 and store the object of class ABC in it.

When we call I1.Show() the version implemented with Interface1 executed and call I2.Show() executes the second version of the method.

Interface Inheritance:

Like classes, we also can inherit one interface from another interface.

The derived class which implements the interface which inherits another interface must provide implementations for all methods in interface inheritance chain.

Example:

using System;
namespace InterfaceInheritanceDemo
{
   interface IFileWriter
   {
      void Write(string str);
   }
   interface IFileReader
   {
      string Read();
   }
   interface IFileOperation : IFileWriter, IFileReader
   {
      void OpenFile(string path);
      void CloseFile();
   }
   class FileOperation : IFileOperation
   {
      string FilePath;
      public void Write(string str)
      {
         Console.WriteLine("{0} '{1}' in {2}", "Writing", str, FilePath);
      }
      public string Read()
      {
         return "Reading a line from file " + FilePath;
      }
      public void OpenFile(string path)
      {
         FilePath = path;
         Console.WriteLine("Opening file: " + path);
      }
      public void CloseFile()
      {
         Console.WriteLine("Closing file: " + FilePath);
      }
   }
   class Program
   {
      static void Main(string[] args)
      {
         FileOperation myFile = new FileOperation();
         myFile.OpenFile("C:/MyTextFile.txt");
         myFile.Write("Learning from KnowledgeTPoint.");
         Console.WriteLine(myFile.Read());
         myFile.CloseFile();
         Console.ReadLine();
      }
   }
}

The output of the program is:

Opening file: C:/MyTextFile.txt
Writing ‘Learning from KnowledgeTpoint.’ in C:/MyTextFile.txt
Reading a line from file C:/MyTextFile.txt
Closing file: C:/MyTextFile.txt

In above program interface IFileOperation inherits methods Write () and Read () from base interfaces IFileWriter and IFileReader respectively.

So the classes which implement the interface IFileOperation must provide the implementation for all methods including these two methods.

So, in conclusion in our program, class FileOperation implements interface IFileOperation, so it must provide an implementation for all methods.

Hence, you might have now understood the interface clearly in C#.

Useful Resource: https://www.tutorialspoint.com/csharp/csharp_interfaces.htm

LEAVE A REPLY

Please enter your comment!
Please enter your name here