In C#, a class can only derive from one base class - which can be abstract or concrete. If none is specified, the class derives directly from
Object
. MS reasoned that adding multiple inheritance added too much complexity to C# while providing too little benefit.
This gives us a problem which is solved via Interfaces - a class can also implement as many Interfaces as it wants (using the same syntax as derivation).
There is some "blurring" going on between abstract classes and interfaces in the latest C# version, now that Interfaces can provide default method implementations, but it's still not quite the same as "full derivation" which is still only possible with a single class.
Quote:
Yes. I knew that. Consider, I have only one interface with few methods. In that case, I can always create a pure abstract class and get my job done. Isn't it?
Then there must be some other reason too why to use interface and not pure abstract class or vice-versa.
It could be related to builds or implementation or security whatever.
I am thinking from all aspects actually.
Please let me know if you also can find out some other points.
Thanks a lot.
There are no other points - it is purely about Single Inheritance.
Think about it: you have a class which has to inherit from
SqlDataReader
for example. That means the class definition must be:
public MyClass : SqlDataReader
{
...
}
Suppose you also want that class to be usable in
foreach
loops: that means it must implement the
IEnumerator
interface
*. Since C# does not allow multiple inheritance,without interfaces you would have to choose between deriving from
SqlDataReader
and
IEnumerator
. But, because you can implement as many Interfaces as you want, you can have your cake and eat it:
public MyClass : SqlDataReader, IEnumerator
{
...
}
Without having the extra complexity (and there is a load of that) that multiple inheritance requires.
* Over simplification, I know - just go with it.