P.G Wisgerhof
P.G Wisgerhof

Reputation: 762

Using Type to define new variable

I was wondering if it is possible to use Type to convert an obect back to its original type. I have my code like this now, but this does not work. I've looked on the internet but what i get are methods with generic types, like this.

public static T method<T>(string name)
{
    return (T)objects[name];
}

But i'm looking for something like this.

public static dynamic GetObject(string name)
{
   Type t = objects[name].GetType();
   t test = (t)objects[name]; <--- Is it possible to do something like this?
}

If this won't work, what would be an good way to get the same result?

Thanks in advance for your responses.

Upvotes: 2

Views: 97

Answers (2)

supercat
supercat

Reputation: 81159

You can use Reflection to create a bound generic Type with a particular Type as a type parameter. Once you have done that, you can use Activator.CreateInstance to create an instance of that type. The generic type that you create could be based on an open generic class which is defined purely for this purpose, since it will be able to do anything with type T that it wants. Note that if T has constraints upon it, the attempt to create the generic type will fail if the attempted type parameter does not satisfy those constraints.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

If you're going to return the named object as dynamic, you don't need the type. Just return it, and the runtime binding will handle this for you (or raise an exception at runtime).

public static dynamic GetObject(string name)
{
   return objects[name];
}

Upvotes: 3

Related Questions