Interfaces in C#

 

Interface is contract to the class through which the class is guaranteed to have the methods, properties or indexers of the interface. When a class implements an Interface it must implement all methods of that interface. 

Let us take the example of MotorVehicle class. The derived classes two-wheeler and four-wheeler has different properties, but the selling information or dealership details of both needs to be saved in database. We need to read and write the data by querying the DB. This function we can implement through an Interface. 

interface IDBFunctions 

{ 

        void ReadData(); 

        void WriteData(); 

} 

 

class Twowheeler : IDBFunctions 

{ 

        public void ReadData() 

        { 

            Console.WriteLine("Implementing Read function"); 

        } 

       

        public void WriteData() 

        { 

            Console.WriteLine("Implementing Write function"); 

        } 

} 

 

class Program 

{ 

        static void Main() 

        { 

            Twowheeler objtwowheeler = new Twowheeler(); 

            objtwowheeler.ReadData(); 

            objtwowheeler.WriteData(); 

        } 

}

 

See the same way we can implement the interface IDBFunctions in fourwheeler class as well and we can implement the methods for that class as well. 

Advantage of Interfaces: 

·        C# does not support multiple Inheritance.ie a class cannot be derived from more than one class.But c# supports implementing multiple interfaces to class there by the multiple inheritance factor can  be achieved in c#.

 

·        We can extend an already existing interface by adding new methods to it.For example, we have mentioned IDBFunctions interface which has two methods, and we can extend this interface by adding a new method to it say method for printing the data.  

interface IPrintData : IDBFunctions 

{ 

       void PrintData(); 

}

 

If an object requires this additional functionality of printing the data it can implement this interface instead of IDBFunctions.So in effect IPrintData interface has three methods readdata() and writedata() from the implemented interface and printdata() which is its own. Classes are now free to implement the interface depending on the functionality required. 

·        We can also combine multiple interfaces to a single interface. This is a great advantage while dealing with huge programs or while enhancing applications. 

 interface IDealdata : IDBFunctions, IPrintData 

{ 

 

}

 

Here the two interfaces IPrintData and IDBFunctions have been combined and formed as a new interface  IDealdata