Sagar
Sagar

Reputation: 292

Which is valid object in C#?

I have one base class Base and a class Derived1 which is derived from Base class and another derived class Derived2 which is dervied from derived1.

Below i have mentioned few cases of object creation ( following by Multilevel inheritance of class ). Can someone help me in understanding those cases in which object creation is not possible and why it is not possible in C# ?

Base b1 = new Base() //Possible 
Base b1 = new derived1() // Possible 
Derived1 d1 = new Base() // Not Possible 
Derived1 d1 = new Derived1() // Possible 
Derived2 d2 = new Derived1() // ---- 
Derived1 d1 = new Derived2() // ---- 
Derived2 d2 = new Derived2() // Possible
Derived2 d2 = new Base() // ---- 
Base b1 = new Derived2() // ---- 

Upvotes: 3

Views: 131

Answers (3)

Erik Philips
Erik Philips

Reputation: 54638

Here is a super easy way:

public class A { }
public class B : A { }
public class C : B { }

So it's as simple as reversing the definitions:

A < B < C

(I'm using the greater than sign here, because B is everything A is and more. C is everything B and A are... and more.)

So A can support A, B and C. And B can support B and C. Lastly C can only support C.

Valid:

A z = new A();
A y = new B();  
A x = new C();
B w = new B();
B v = new C();
C u = new C();

Any other combination is not supported by C# (because of Liskov's substitution principle).

Upvotes: 5

Mohit
Mohit

Reputation: 1234

Derived class has all the information about the base class, as inheritance is a "is-a" relationship.

We have a base class "Base" and a derived class "Derived"

according to inheritance rule "Derived is-a Base". All the properties of Base is present in Derived.

Base b = new Derived(); //It is possible as Derived as all the information about base.

Dervied d = new Base(); //It is not possible because base don't have the information about derived.

Upvotes: 1

Jakub Szumiato
Jakub Szumiato

Reputation: 1318

That's easy. The reference (variable declared, so left hand side) must be of less derived type. The instance on the right side may be more derived.

Upvotes: 0

Related Questions