C# inheritance casting one child to another

c#, casting, inheritance

Solution

It's not possible because the object `objA` refers to is not a `ChildB`. To put it another way, here's an example of what you're trying to do:

 string x = "hi";
 FileStream y = (FileStream) x;

They both have a common parent - `System.Object` - but they're completely different classes. What would you expect to happen if you tried to read from `y`?

Suppose your `ChildB` type has some field which is specific to that type - what would you expect that field's value to be after casting `objA`?

Why do you want to pretend that a `ChildA` is actually a `ChildB`? Could you maybe add a method in the parent class which does what you want? Add a method in `ChildA` like this:

ChildB ToChildB()

to perform an appropriate conversion?

Problem

I have this simple structure: 1 parent, and two different childs. ``` public class Parent{} public class ChildA : Parent{} public class ChildB : Parent{} ``` I have an object objA of type ChildA, which I want to cast to ChildB. My naive approach says: ``` ChildA objA = new ChildA(); ChildB objB = (ChildB)objA; ``` But this is not directly possible - why? Is this because I need to implement some functions or because my naive approach is wrong? Regards, Casper

Original source