Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast object to type described by Type class?

I have a object:

ExampleClass ex = new ExampleClass(); 

And:

Type TargetType 

I would like to cast ex to type described by TargetType like this:

Object o = (TargetType) ex; 

But when I do this I get:

The type or namespace name 't' could not be found

So how to do this? Am I missing something obious here?

Update:

I would like to obtain something like this:

public CustomClass MyClassOuter {    get    {         return (CustomClass) otherClass;    } }  private otherClass; 

And because I will have many properties like this I would like do this:

public CustomClass MyClassOuter {    get    {         return (GetThisPropertyType()) otherClass;    } }  private SomeOtherTypeClass otherClass; 

Context:

Normally in my context in my class I need to create many properties. And in every one replace casting to the type of property. It does not seem to have sense to me (in my context) because I know what return type is and I would like to write some kind of code that will do the casting for me. Maybe it's case of generics, I don't know yet.

It's like I can assure in this property that I get the right object and in right type and am 100% able to cast it to the property type.

All I need to do this so that I do not need to specify in every one property that it has to "cast value to CustomClass", I would like to do something like "cast value to the same class as this property is".

For example:

class MYBaseClass {    protected List<Object> MyInternalObjects; }  class MyClass {    public SpecialClass MyVeryOwnSpecialObject    {       get       {            return (SpecialClass) MyInteralObjects["MyVeryOwnSpecialObject"];       }    } } 

And ok - I can make many properties like this one above - but there is 2 problems:

1) I need to specify name of object on MyInternalObjects but it's the same like property name. This I solved with System.Reflection.MethodBase.GetCurrentMethod().Name.

2) In every property I need to cast object from MyInternalObjects to different types. In MyVeryOwnSpecialObject for example - to SpecialClass. It's always the same class as the property.

That's why I would like to do something like this:

class MYBaseClass {    protected List<Object> MyInternalObjects; }  class MyClass {    public SpecialClass MyVeryOwnSpecialObject    {       get       {            return (GetPropertyType()) MyInteralObjects[System.Reflection.MethodBase.GetCurrentMethod().Name];       }    } } 

And now concerns: Ok, what for? Because further in my application I will have all benefits of safe types and so on (intellisense).

Second one: but now you will lost type safety in this place? No. Because I'm very sure that I have object of my type on a list.

like image 279
Tom Smykowski Avatar asked Jul 30 '09 12:07

Tom Smykowski


People also ask

How do you cast an object to a specific class?

Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object. Return Value: This method returns the specified object after casting in the form of an object.

Which is used for casting of object to a type or a class?

Typecasting is the assessment of the value of one primitive data type to another type. In java, there are two types of casting namely upcasting and downcasting as follows: Upcasting is casting a subtype to a super type in an upward direction to the inheritance tree.

Which keyword is used to cast an object into another type?

You convert an Object variable to another data type by using a conversion keyword such as CType Function.

Can you type cast an object in Java?

Type Casting in Java – An Introduction Here, the concept of Type casting in Java comes into play. Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind or Object, and the process of conversion from one type to another is called Type Casting.


2 Answers

Object o = (TargetType) ex; 

This code is useless. You might have a type on the right but it's still only an object on the left side. You can't use functionality specific to TargetType like this.


This is how you can invoke a method of an unknown object of a given type:

object myObject = new UnknownType(); Type t = typeof(UnknownType); // myObject.GetType() would also work MethodInfo sayHelloMethod = t.GetMethod("SayHello"); sayHelloMethod.Invoke(myObject, null); 

With this UnknownType class:

class UnknownType {     public void SayHello()     {         Console.WriteLine("Hello world.");     } } 
like image 80
weiqure Avatar answered Oct 04 '22 05:10

weiqure


Usually a desire to do this indicates a misunderstanding. However, there are very occasionally legitimate reasons to do this. It depends on whether or not it's going to be a reference conversion vs an unboxing or user-defined conversion.

If it's a reference conversion, that means the actual value (the reference) will remain entirely unchanged. All the cast does is perform a check and then copy the value. That has no real use - you can perform the check using Type.IsAssignableFrom instead, and just use the implicit cast to object if you want it in a variable of type object.

The main point of casting is to provide the compiler with more information. Now if you only know the type at execution time, that clearly can't help the compiler.

What do you plan to do with o after you've performed the cast? If you can explain that, we can try to explain how to achieve the effect you're after.

If you really want a user-defined conversion or an unboxing conversion to occur, that could be a different matter - but I suspect that's not the case.

EDIT: Having seen your update, your property is just declared to return CustomClass, so all you need is:

public CustomClass MyClassOuter {    get    {         return (CustomClass) otherClass;    } } 

I suspect you still haven't really given us all the information we need. Is that definitely how your property will be defined, with CustomClass being a definite type? Why were you trying to perform the cast dynamically when you know the property type?

EDIT: It sounds like you're just trying to save some typing - to make it easier to cut and paste. Don't. You know the type at compile-time, because you know the type of the property at compile-time (it's specified in the code just a few lines above). Use that type directly. Likewise don't try to get the name of the current method to work out the key to use. Just put the name in directly. Again, you know it at compile-time, so why be dynamic? I'm all for laziness when it makes sense, but in this case it just doesn't.

like image 35
Jon Skeet Avatar answered Oct 04 '22 04:10

Jon Skeet