Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 302
TCM Avatar asked Nov 23 '10 15:11

TCM


People also ask

What is the purpose of casting an object to another type?

Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.

Does casting change the type?

It only changes when you assign a new object. (It never changes for a given object, no object instance can change its class). The cast bridges the two: It checks the runtime type and then allows you to declare that type.

Can I typecast an object in Java?

Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind of Object, and the process of conversion from one type to another is called Type Casting. Before diving into the typecasting process, let's understand data types in Java.


1 Answers

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.

like image 54
jason Avatar answered Sep 18 '22 05:09

jason