Basically, interfaces are a way to provide some kind of multiple inheritance in C#.
Because you can only derive a class from a single base class (or things start to get very confusing) it is difficult to provide additional features without it. A Base class describes what a class is - Interfaces describe what a class can do.
They provide a contract: "If you implement the required bits, you can be treated as one of us". For example, if your Students class is derived from People, and implements IEnumerable, then it has all the features of People, but it can also be used in a foreach loop.
Where classes implement the same interface, they call all be used in the same way, and through the same method set, despite being unrelated classes otherwise.
Also see here:
http://msdn.microsoft.com/en-us/library/87d83y5b(v=vs.80).aspx[
^]
and here:
http://en.wikibooks.org/wiki/C_Sharp_Programming/Interfaces[
^]
"So if it is necessary to define each and every thing in the class that implements interface then why do we need interface,we can declare and define all the things in that class only. This is the main doubt i have as we have to define each method and variables in the implementing class then we can declare these variables in that class only then there is no need of interface rite?"
No. :laugh:
Let's ignore computers for a moment.
When I went to University (a long time ago) it was what is called a "closed shop" - it was a legal requirement to join the Students Union (the one and only labour union I have ever joined) and until you had joined (and paid the annual fee, lets not forget the Union Dues) you couldn't attend lectures, you couldn't join the Union Bar (where they sold cheap beer as it was a membership club), you couldn't join any of the University social clubs. Because all of them required you to sign on with your Student Union membership card to prove you had a right to be a member: you attended the right university. There is very likely something similar in your country.
If you think of UnionMembership as an Interface it conveyed nothing. Provided no benefits. My Student class had to implement the UnionMembership to get it's Property: UnionMembership.MemberCard - and execute it's method: PayFeeEveryYear(double lots).
But my student had to be a Person (which includes a lot more properties and methods) many of which the Student class doesn't need to affect: Name, address, social security number, parents, ...
But you can't inherit from two unrelated classes! Understandably, it was decided that this was way too complex and gave too many problems in practice.
An Interface gives us not a way to derive from two classes, but instead a way to derive from a base class (Person) and include a membership of another class, and to get all the benefits that such a membership confers:
public class Student : Person, IUnionMembership
{
...
}
Does that make sense?