wasAsked.

Will this work: DerivedClass drive = new BaseClass();

Impetus · Role not specified · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

No. DerivedClass d = new BaseClass(); does not compile. The compiler reports error CS0266: "Cannot implicitly convert type 'BaseClass' to 'DerivedClass'. An explicit conversion exists (are you missing a cast?)" Why - Every DerivedClass is a BaseClass, but not every BaseClass is a DerivedClass. - A variable of type DerivedClass promises that the object has all derived members (extra fields and methods). A BaseClass object does not have them, so the assignment would break type safety. public class BaseClass { public void BaseMethod() { } } public class DerivedClass : BaseClass { public void DerivedMethod() { } } DerivedClass d = new BaseClass(); // compile error // If allowed, d.DerivedMethod() would call a method the object does not have. What about an explicit cast? DerivedClass d = (DerivedClass)new BaseClass(); This compiles, but throws InvalidCastException at runtime, because the actual object is a BaseClass, not a DerivedClass. What does work 1. Upcasting (implicit, always safe) BaseClass b = new DerivedClass(); // OK: a derived object is a base object b.BaseMethod(); // b.DerivedMethod(); — not accessible through a BaseClass reference (compile error) 2. Downcasting when the object really is derived BaseClass b = new DerivedClass(); DerivedClass d = (DerivedClass)b; // OK at runtime: the object is a DerivedClass 3. Safe downcasting with pattern matching or as if (b is DerivedClass derived) derived.DerivedMethod(); DerivedClass? maybe = b as DerivedClass; // null if the object is not a DerivedClass Related concept: with a base reference pointing to a derived object, virtual methods overridden in the derived class run the derived implementation (runtime polymorphism), while members hidden with new run the base version. Summary: a base object cannot be assigned to a derived variable — the compiler prevents it, and forcing it with a cast fails at runtime unless the object really is of the derived type.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics