Interface in C#

Using Interface in c#

What is an Interface?

1.An Interface is similar type of class. Instead of class keyword we use an Interface keyword.
2.It don't have an implementation, contain method signatures the all are abstract method.
3.In Interface we can define , properties, events and indexers.


Why we use an Interface?

1.The reason of use Interface because Interface only provide declaration and inherit by class and struct though the each interface provide them to Implement.
2.Interface is Replacement of an multiple Inheritance.

Interface are  2 Type.

Implement Interface
Implement Interface explicitly.


Program:- Implement Interface


Interface IVehicle
{
 void Start();
void Stop();
}


Class Car: IVehicle
{
public void Start()
{
Console.WriteLine("KeyDown");
}
public void Stop()
{
Console.WriteLine("KeyUp");
}
}

--------------------------------------------------
Implement Interface explicitly.

Suppose Two different interface have same method declaration or signature.

ex:-

Interface Icar
{
 void start();
}

Interface Ibike
{
 void start();
}

Class Vehicle: Icar, Ibike
{
       void Icar.start()  //------Access Specifier not required in explicitly
       {
        Console.WriteLine("Key");
       }                        
       void Ibike.start()
      {
         Console.WriteLine("Kick");
      }
}

public static void Main(string[] str)
{
   Vehicle v= new Vehicle();
   Icar car= v;
   Ibike bike = v;
   car.start();
   bike.start();
}


Share this

Previous
Next Post »