What is interface in c# with example

An interface is defined as a syntactical contract that every one the categories inheriting the interface should follow. The interface defines the ‘what’ part of} the syntactic contract and also the deriving categories define the ‘how’ part of the syntactical contract.

Interfaces define properties, methods, and events, which area unit the members of the interface. Interfaces contain solely the declaration of the members. it’s the responsibility of the deriving category to define the members. It typically helps in providing a standard structure that the deriving categories would follow.

Abstract categories to some extent serve constant purpose, however, {they area unit|they’re} mostly used once only few ways are to be declared by the base category and the explanation category implements the functionalities.

Declaring Interfaces

 interface IModem
 {
 public bool Open();
 public bool Close();
 public int Read();
 public int Write(byte[] buffer);
 }

Interfaces are declared victimization the interface keyword. it’s similar to category declaration. Interface statements area unit public by default. Following is associate example of an interface declaration:

Example

The below example demonstrates implementation of the above interface

interface IModem
 {
 public bool Open();
 public bool Close();
 public int Read();
 public int Write(byte[] buffer);
 }
public class AirtelModem:IModem
 {


 public bool Open()
 {
 throw new NotImplementedException();
 }

public bool Close()
 {
 throw new NotImplementedException();
 }

public int Read()
 {
 throw new NotImplementedException();
 }

public int Write(byte[] buffer)
 {
 throw new NotImplementedException();
 }
 }

public class BsnlModem : IModem
 {


 public bool Open()
 {
 throw new NotImplementedException();
 }

public bool Close()
 {
 throw new NotImplementedException();
 }

public int Read()
 {
 throw new NotImplementedException();
 }

public int Write(byte[] buffer)
 {
 throw new NotImplementedException();
 }
 }
public static void Main()
 {
 IModem objAirtel = new AirtelModem();
 IModem objBsnl = new BsnlModem();
 }

The only difference between the earlier code and this code is within the category mental representation. within the earlier case we have a tendency to use AirtelModem and within the latter case we have a tendency to use BsnlModem. the remainder of the code remains constant. this can be the best advantage of making interfaces—we don’t got to change a lot of of the code even after we change modems. This makes it easier to put in writing Associate in Nursing application that works with lots of various modems. Here, we will see that our initial concern for a way to produce a special implementation for every modem associate degreed yet maintaining one interface to access them is well resolved using an interface.

Leave a Reply

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