Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why object(root) class does not clashes multiple inheritance

Tags:

c#

.net

oop

As we know .Net does not support multiple inheritance. Thus we can only inherit only one class. But every class by default inherits 'object' class. so why not error occurs when I inherit any other class.

For example A- Base class, B- Derived Class. When I use A:B , implicitly object class also get inherited as( I think) A:B,Object . How can it be possible if .Net does not support multiple inheritance.

like image 422
Rajaram Shelar Avatar asked Sep 25 '12 06:09

Rajaram Shelar


2 Answers

No, it's not like that - there's only one inheritance chain, which would be:

__________
| Object |
----------
    ^
    |
__________
|   A    |
----------
    ^
    |
__________
|   B    |
----------

Any one class only has one direct base class, but the inheritance chain of classes can be long.

As an example of why this isn't the same as B inheriting directly from A, if A overrides ToString, there's no way of B calling the original implementation of Object.ToString() - it can only call A's version (and override ToString itself, of course).

like image 115
Jon Skeet Avatar answered Nov 10 '22 00:11

Jon Skeet


It's simple, the declared class only inherits from object if it does not inherit from another class. What the compiler does is that it effectively changes

public class MyBaseLessClass
{
}

to

public class MyBaseLessClass : object
{
}

so that each and every class has exactly one class it inherits from. (a bit like the barber paradox :))

like image 32
SWeko Avatar answered Nov 09 '22 22:11

SWeko