Is it possible to assign a base class object to a derived class reference with an explicit typecast?

Maddy.Shik picture Maddy.Shik · Apr 8, 2009 · Viewed 130.6k times · Source

Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?.

I have tried it and it creates a run-time error.

Answer

Jon Skeet picture Jon Skeet · Apr 8, 2009

No. A reference to a derived class must actually refer to an instance of the derived class (or null). Otherwise how would you expect it to behave?

For example:

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

If you want to be able to convert an instance of the base type to the derived type, I suggest you write a method to create an appropriate derived type instance. Or look at your inheritance tree again and try to redesign so that you don't need to do this in the first place.