Can some one explain the exact use of interfaces in C# ?
This has been discussed so many times here in the past that it is hard to pick any one duplicate for this question.
To save the time of repeating what has been said before, try this search, and start going through the results.
In the most simple terms, an Interface expresses what one, or more classes can do, although the implimentation may vary across the various classes.
Polymorphism You can use 2 classes that implement the same interface without having to know exactly which concrete class it is. It aids in keeping code loosely coupled.
Imagine the the situation of having a factory that creates cars. You know that every vehicle has an engine and can be started, so you have the following:
interface IVehicle
{
Engine vehicleEngine { get; set; }
bool StartEngine();
}
Now, the factory makes an array of other vehicles, so for instance a truck and a normal car:
public Car : IVehicle
{
// MUST implement vehicleEngine and StartEngine:
public Engine vehicleEngine { get; set; }
public bool StartEngine()
{
// Cars needs to do xyz to start
}
public int MaxNumberOfPassenger { get; set; } // Specific to Car
}
and then:
public Truck : IVehicle
{
// MUST implement vehicleEngine and StartEngine:
public Engine vehicleEngine { get; set; }
public bool StartEngine()
{
// Trucks needs to do abc to start
}
public int MaximumLoad { get; set; } // Specific to Truck
}
This therefore forces all vehicles to implement specific members to fall under the category of a vehicle, but then can also be specialized with their own distinct members.
An interface defines the minimum requirements that a class that can be instantiated must implement. It expresses this through methods.
For instance, an interface could define a function called Foo which takes an integer and returns a boolean:
public interface ICanFoo
{
bool Foo(int number);
}
Any class which implements this interface must also implement this method:
public class Fooable : ICanFoo
{
public bool Foo(int number)
{
// do something
}
}
The implementation within the method is up to the specific classes which are implementing the interface.
By using interfaces you no longer care about implementation are compile time, but rather specification. You can call it like this:
ICanFoo myFooable = ...
bool success = fooable.Foo(4);
The actual type of fooable can be any class that implements ICanFoo since you know that ICanFoo will always define a method implementation for the Foo method.
this may help you http://dotnet.dzone.com/articles/concept-interfaces-c?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+zones/dotnet+(.NET+Zone)