How to cast object to type described by Type class?

82,942

Solution 1

Now it seems to be impossible, but soon will be available with new feature in .NET 4.0 called "dynamic":

http://www.codeguru.com/vb/vbnet30/article.php/c15645__4/

Solution 2

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.");
    }
}

Solution 3

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.

Solution 4

if (ex is ExampleClass) 
{
  ExampleClass myObject = (ExampleClass)ex;
}

That would do it but I guess the question is what are you trying to achieve and why? I often find that if something seems really, really difficult then I'm probably doing it wrong.

Share:
82,942
Tom Smykowski
Author by

Tom Smykowski

Updated on January 07, 2020

Comments

  • Tom Smykowski
    Tom Smykowski over 4 years

    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.