vineel
vineel

Reputation: 205

can I typecast one subclass to other subclass object in C#

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

Answers (6)

adelphus
adelphus

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

Jeb
Jeb

Reputation: 3799

Not possible. Classes C and B are not related in the class hierachy.

Upvotes: 1

BrokenGlass
BrokenGlass

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

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

No, you can't. If you want to copy properties from one class to another, you might consider AutoMapper.

Upvotes: 1

Chuck Norris
Chuck Norris

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

Alex Dn
Alex Dn

Reputation: 5553

You can not. What you can is cast B to A.

Upvotes: 2

Related Questions