I am trying to cast from a parent class to a child class but I get an InvalidCastException. The child class only has one property of type int. Does anyone know what I need to do?
I am trying to cast from a parent class to a child class but I get an InvalidCastException. The child class only has one property of type int. Does anyone know what I need to do?
The instance that your base class reference is referring to is not an instance of your child class. There's nothing wrong.
More specifically:
Base derivedInstance = new Derived();
Base baseInstance = new Base();
Derived good = (Derived)derivedInstance; // OK
Derived fail = (Derived)baseInstance; // Throws InvalidCastException
For the cast to be successful, the instance that you're downcasting must be an instance of the class that you're downcasting to (or at least, the class you're downcasting to must be within the instance's class hierarchy), otherwise the cast will fail.
I have seen most of the people saying explicit parent to child casting is not possible, that actually is not true. Let's take a revised start and try proving it by examples.
As we know in .net all castings have two broad categories.
Reference type has further three main situational cases in which any scenario can lie.
Case 1. Child to any direct or indirect parent
Employee e = new Employee();
Person p = (Person)e; //Allowed
Case 2. Parent variable holding parent object (Not allowed)
Person p = new Person(); // p is true Person object
Employee e = (Employee)p; //Runtime err : InvalidCastException <-------- Yours issue
Case 3. Parent variable holding child object (Always Successful)
Note: Because objects has polymorphic nature, it is possible for a variable of a parent class type to hold a child type.
Person p = new Employee(); // p actually is Employee
Employee e = (Employee)p; // Casting allowed
Conclusion : After reading above all, hope it will make sense now like how parent to child conversion is possible(Case 3).
Answer To The Question :
Your answer is in case 2.Where you can see such casting is not allowed by OOP and you are trying to violate one of OOP's basic rule.So always choose safe path.
Further more, to avoid such exceptional situations .net has recommended using is/as operators those will help you to take informed decisions and provide safe casting.
As of C# 7.0, you can use the is keyword to do this :
With those class defined :
class Base { /* Define base class */ }
class Derived : Base { /* Define derived class */ }
You can then do somehting like :
void Funtion(Base b)
{
if (b is Derived d)
{
/* Do something with d which is now a variable of type Derived */
}
}
Which would be equivalent to :
void Funtion(Base b)
{
Defined d;
if (b is Derived)
{
d = (Defined)b;
/* Do something with d */
}
}
You could now call :
Function(new Derived()); // Will execute code defined in if
As well as
Function(new Base()); // Won't execute code defined in if
That way you can be sure that your downcast will be valid and won't throw an exception !
As for me it was enough to copy all property fields from the base class to the parent like this:
using System.Reflection;
public static ChildClass Clone(BaseClass b)
{
ChildClass p = new ChildClass(...);
// Getting properties of base class
PropertyInfo[] properties = typeof(BaseClass).GetProperties();
// Copy all properties to parent class
foreach (PropertyInfo pi in properties)
{
if (pi.CanWrite)
pi.SetValue(p, pi.GetValue(b, null), null);
}
return p;
}
An universal solution for any object can be found here
To cast, the actual object must be of a Type equal to or derived from the Type you are attempting to cast to...
or, to state it in the opposite way, the Type you are trying to cast it to must be the same as, or a base class of, the actual type of the object.
if your actual object is of type Baseclass, then you can't cast it to a derived class Type...