Rajeshwaran S P Rajeshwaran S P - 5 days ago 6
C# Question

Single Inheritance in C# - object class?

I have been asking myself this question for a long time now. Thought of posting it. C# doesn't support Multiple Inheritance(this is the fact). All classes created in C# derive out of 'Object' class(again a fact).

So if C# does not support Multiple inheritance, then how are we able to extend a class even though it already extends Object class?

Illustating with an example:


  1. class A : object - Class A created.

  2. class B : object - Class B created.

  3. class A : B - this again is supported. What happens to the earlier association to object.



We are able to use object class methods in A after step 3. So is the turned to multi level inheritance. If that is the case, then


  1. class A : B

  2. class C : B

  3. class A : C - I must be able to access class B's methods in A. Which is not the case?



Can anyone please explain?

Answer

Joel's answer is correct. There is a difference between multiple inheritance and an inhertance tree (or derivation chain). In your example, you actually show an inhertance tree: One object inherits (derives) from another object higher in the tree. Multiple inheritance allows one object to inherit from multiple base classes.

Take, for example, the following tree:

public class BaseClass { }

public class SpecialBaseClass : BaseClass {}

public class SpecialtyDerivedClass : SpecialBaseClass {}

This is perfectly valid and says that SpecialtyDerivedClass inherits from SpecialBaseClass (SpecialtyDerivedClass' parent) which, in turn, derives from BaseClass (SpecialtyDerivedClass' grandparent).

Under the idea of multiple inheritance, the example would look like this:

public class BaseClass { }

public class SpecialBaseClass {}

public class SpecialtyDerivedClass : BaseClass, SpecialBaseClass {}

This is not allowed in .NET, but it says that SpecialityDerivedClass inherits from both BaseClass and SpecialBaseClass (which are both parents).

.NET does allow a form of multiple inheritance by allowing you to inherit from more than one interface. Changing the example above slightly:

public class BaseClass { }

public interface ISpecialBase {}

public interface ISpecialDerived {}

public class SpecialtyDerivedClass : BaseClass, ISpecialBase, ISpecialDerived {}

This says that SpecialtyDerivedClass inherits from BaseClass (it's parent) and also ISpecialBase and ISpecialDerived (also parent's but more like step-parents as interfaces can't specify functionality).