Answer the question
In order to leave comments, you need to log in
Why doesn't C# allow you to downcast from parent to child?
I wonder why C# fundamentally does not allow you to extend the base instance, as in this code?
class People { public string name; }
class Person : People { public uint id; }
static void Main(string[] args)
{
People jack = new People { name = "Jack" };
Person jack_passport = (Person)jack; // InvalidCastException
}
Answer the question
In order to leave comments, you need to log in
I wonder why C# fundamentally does not allow you to extend the base instance, as in this code?
I want to understand on a theoretical level.
Why does it seem logical to you to cast a parent instance into a child instance? And if the descendant defines the special conditions that are needed for its creation? What about dependencies?
It is strange that the following was not written here:
class People { public string name; }
class Person : People { public uint id; }
static void Main(string[] args)
{
People jack = new Person { name = "Jack" }; // Upcast
Person jack_passport = (Person)jack; // Downcast
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question