Unable to Cast from Parent Class to Child Class

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?


Solution 1:

A simple way to downcast in C# is to serialize the parent and then deserialize it into the child.

 var serializedParent = JsonConvert.SerializeObject(parentInstance); 
 Child c  = JsonConvert.DeserializeObject<Child>(serializedParent);

I have a simple console app that casts animal into dog, using the above two lines of code over here

Solution 2:

You can't cast a mammal into a dog - it might be a cat.

You can't cast a food into a sandwich - it might be a cheeseburger.

You can't cast a car into a Ferrari - it might be a Honda, or more specifically, You can't cast a Ferrari 360 Modena to a Ferrari 360 Challange Stradale - there are differnt parts, even though they are both Ferrari 360s.

Solution 3:

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.

Solution 4:

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.

  1. For Value type
  2. For Reference type (in your case its reference type)

Reference type has further three main situational cases in which any scenario can lie.

Child to Parent (Implicit casting - Always successful)

Case 1. Child to any direct or indirect parent

Employee e = new Employee();
Person p = (Person)e; //Allowed

Parent to Child (Explicit casting - Can be successful)

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.

Solution 5:

There are some cases when such a cast would make sense.
I my case, I was receiving a BASE class over the network, and I needed more features to it. So deriving it to handle it on my side with all the bells and whistles I wanted, and casting the received BASE class into the DERIVED one was simply not an option (Throws InvalidCastException of Course)

One practical think-out-of-the-box SOLUTION was to declare an EXTENSION Helper class that was NOT inheriting BASE class actually, but INCLUDING IT as a member.

public class BaseExtension
{
   Base baseInstance;

   public FakeDerived(Base b)
   {
      baseInstance = b;
   }

   //Helper methods and extensions to Base class added here
}

If you have loose coupling and just need a couple of extra features to base class without REALLY having an absolute need of derivation, that could be a quick and simple workaround.