Radu M.
Radu M.

Reputation: 1391

get the Type for a object declared dynamic

I would like to get the Type for an dynamic object, something like:

dynamic tmp = Activator.CreateInstance(assembly, nmspace + "." + typeName);
Type unknown = tmp.GetType();

Except that in the above, GetType() returns the type of the wrapper for dynamic objects not the type of the wrapped object. Thanks!

Upvotes: 32

Views: 43535

Answers (2)

unruledboy
unruledboy

Reputation: 2342

If you can use Activator.CreateInstance, you can directly use:

object tmp = Activator.CreateInstance(assembly, nmspace + "." + typeName);
Type unknown = tmp.GetType();

Upvotes: 2

Eric Farr
Eric Farr

Reputation: 2713

You need to do this...

Type unknown = ((ObjectHandle)tmp).Unwrap().GetType();

By the way, this is a little confusing because if you call Activator.CreateInstance on a type in your current assembly...

Activator.CreateInstance(typeof(Foo))

...the object is not wrapped and the original code works fine.

Upvotes: 37

Related Questions