2

As long as I know, we can't directly convert a base class to a derived (sub) class, because the base is not an instance of the derived and thus it'll result in null.

I have two classes, one derives from the other. I'm trying to figure out why I can convert baseClass1 to Sub without resulting in null while I can't convert the baseClass2 to Sub because it results in null.

Base baseClass1 = new Sub(); // The result is an instance of Base
Base baseClass2 = new Base(); // Same thing
Sub subClass1 = (Sub)baseClass1; // Doesn't result in null
Sub subClass2 = (Sub)baseClass2; // Does result in null

the baseClass1 is an instance of Base, even though I used the Sub() constructor. But using the Sub() constructor somehow allows me to convert the instance of Base to an instance of Sub without even losing the values that extra members of the Sub class hold (let's say I passed those values through the Sub() constructor in the first line).

What's the logic behind this? What is the true difference between baseClass1 and baseClass2, even though they're both instances of Base?

Ramtin Soltani
  • 2,650
  • 3
  • 24
  • 45

3 Answers3

2

the baseClass1 is an instance of Base, even though I used the Sub() constructor.

That is totally not true. baseClass1 is an instance of Sub assigned to variable typed as Base. That's why you can cast it back to Sub.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

This is because baseClass1 actually references an instance of Sub. You cannot cast an instance of a base class to that of a derived class. That is why the second cast fails.

object o = new object();
string s = (string) o;
int i = s.Length; // What can this sensibly do?

Ref: https://stackoverflow.com/a/729532

Community
  • 1
  • 1
imlokesh
  • 2,506
  • 2
  • 22
  • 26
1

It doesn't matter what type you declare baseClass1 to be, it's what actual instance its points to that is important, therefore even though you typed it as Base the allocated type on the heap is actually Sub... Hence casting to Sub is fine

Paul Carroll
  • 1,523
  • 13
  • 15