Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the Type for a object declared dynamic

Tags:

c#

types

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!

like image 307
Radu M. Avatar asked Sep 09 '11 13:09

Radu M.


People also ask

What is the dynamic type in C#?

C# 4 introduces a new type, dynamic . The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object . At compile time, an element that is typed as dynamic is assumed to support any operation.

What is dynamic data type?

Dynamic data types are dynamic in nature and don't require initialization at the time of declaration. It also means that a dynamic type does not have a predefined type and can be used to store any type of data. We can define this data type using the keyword “dynamic" in our code.

Is it good to use dynamic type in C#?

It is definitely a bad idea to use dynamic in all cases where it can be used. This is because your programs will lose the benefits of compile-time checking and they will also be much slower.

What is an ExpandoObject?

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject. sampleMember instead of more complex syntax like sampleObject.


1 Answers

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.

like image 88
Eric Farr Avatar answered Sep 26 '22 01:09

Eric Farr