Inheritance


Why C# does not support multiple class inheritance
Why C# does not support multiple class inheritance?
or
What are the problems of multiple class inheritance?
C# does not support multiple class inheritance because of the diamond problem that is associated, with multiple class inheritance. Let us understand the diamond problem of multiple class inheritance with an example.

As shown in the image above:
1. I have 2 classes - ClassB and ClassC

2. Both of these classes inherit from ClassA
3. Now, we have another class, ClassD which inherits from both ClassB and ClassC
So, if a method in ClassD calls a method defined in ClassA and ClassD has not overriden the invoked method. But both ClassB and ClassC have overridden the same method differently. Now, the ambiguity is, from which class does, ClassD inherit the invoked method: ClassB, or ClassC?

In order not to have these problems, C# does not support multiple class inheritance.

What are the difference between interfaces and abstract classes

There are several differences between an abstract class and an interface as listed below.
1. Abstract classes can have implementations for some of its members, but the interface can't have implementation for any of its members.

2. Interfaces cannot have fields where as an abstract class can have fields.

3. An interface can inherit from another interface only and cannot inherit from an abstract class, where as an abstract class can inherit from another abstract class or another interface.
4. A class can inherit from multiple interfaces at the same time, where as a class cannot inherit from multiple classes at the same time.

5. Abstract class members can have access modifiers where as interface members cannot have access modifiers.

Another common C# Interview Question, that is commonly asked is, When do you choose interface over an abstract class or vice versa?

A general rule of thumb is, If you have an implementation that will be the same for all the derived classes, then it is better to go for an abstract class instead of an interface. So, when you have an interface, you can move your implementation to any class that implements the interface. Where as, when you have an abstract class, you can share implementation for all derived classes in one central place, and avoid code duplication in derived classes.

No comments:

Post a Comment