Reputation: 205
I want to type cast a below:
Class A
{
}
Class B : A
{
}
Class C: A
{
}
Class D{
B b = new b();
C c = (C) b;
}
Please suggest how can I type cast class C to Class B
Upvotes: 3
Views: 632
Reputation: 10326
Animal
{
}
Giraffe : Animal
{
}
Shark : Animal
{
}
Your question is how do you turn a Giraffe into a Shark. Unfortunately, it can't be done.
Upvotes: 1
Reputation: 160922
No, that's not possible since B is not a C, so this cast must fail. One workaround would be to implement a custom explicit conversion operator but otherwise there is no way - you can only cast to a more specific type (downcast) or to a base class (upcast) in the same inheritance tree.
Upvotes: 5
Reputation: 19956
No, you can't. If you want to copy properties from one class to another, you might consider AutoMapper.
Upvotes: 1
Reputation: 15190
It's simply impossible. You can't to such conversion.
In fact they have same base class, but they aren't same. For example, take a look at this.
Triangle
is Shape
and
Rectangle
is Shape
But you can't convert Triangle
to Rectangle
, because they are different.
Upvotes: 2