Search code examples
c#user-controlscastingas-operator

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 :)


Solution

  • 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.