TCM
TCM

Reputation: 16900

Casting one object to another type

I have one class named A and one class B

public class A : UserControl { }

public class B : UserControl { }

Now i have one assembly whose class's function accepts objects of class A. This assembly is not created by me so i don't have any control. Basically it is 3rd party assembly.

But i want to supply my objects of class B since it is bit customized. Rest assured it contains all properties of class A. How can i typecast my object of class B to type A so that i can integrate 3rd party assembly in my project as well as customize the look and feel according to my needs?

If i so something like (A)objB it is not allowed. Then i tried this:

UserControl control = objB as UserControl;

A objA = control as A;

But problem in this case is objA is null.

To avoid confusion: class A and assembly is provided by 3rd party.

Thanks in advance :)

Upvotes: 5

Views: 6915

Answers (6)

jason
jason

Reputation: 241621

Given your hierarchy, you will have to write a conversion operator. There is no built-in way to do this in general (think Dog : Animal and Cat : Animal):

public static explicit operator A(B b) {
    // code to populate a new instance of A from b
}

You could also use a generic reflection framework and do something like

public static void PropertyCopyTo<TSource, TDesination>(
    this TSource source,
    TDestination destination
) {
    // details elided
}

so then you could say

// b is B
// a is A
b.PropertyCopyTo<A>(a);

which would copy all the common properties between b to a.

Upvotes: 4

Mauro
Mauro

Reputation: 2070

I think you actually cannot do it.

Why not adding your properties to a partial class A?

Upvotes: -1

Nicolas Repiquet
Nicolas Repiquet

Reputation: 9255

For B to be castable to a A, B must inherits A. Even if B contains all properties of A, it's still not a A.

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160862

If B cannot be cast to A (as in B is A) it is not possible to achieve what you are trying to do without inheriting from A. Unfortunately C# doesn't support duck typing unlike many dynamic languages (i.e. Ruby).

Upvotes: 0

Torbj&#246;rn Hansson
Torbj&#246;rn Hansson

Reputation: 19423

You can inherit from class A:

public class B : A {
}

And if you need to overrride some methods/properties just set them to virtual in class A.

Upvotes: -1

TalentTuner
TalentTuner

Reputation: 17556

you may use an Adapter pattern

See Here

Upvotes: 1

Related Questions