I have a class ObjectMapper<T>
. Is there any way in .NET 4.0 to tell if typeof(T)
is dynamic
? I want to be able to determine inside a member method whether the class was initialized as new ObjectMapper<dynamic>()
vs. new ObjectMapper<SomeConcreteClass>()
.
views:
89answers:
2
+6
A:
There is no CLR type called dynamic
. The C# compiler makes all dynamic values of type object
and then calls custom binding code to figure out how to handle them. If dynamic
was used, it will show up as Object
.
Gabe
2010-07-18 21:58:55
Yes, I can see that with a debugger. But is there a way to tell the difference between new ObjectMapper{object}() vs new ObjectMapper{dynamic}()?
Dmitry
2010-07-18 21:59:57
No, you can't tell the difference in your code because the only difference is in how it's used.
Gabe
2010-07-18 22:02:17
Which IMO was a horrible design decision by the C# team, as C# now enters Java-land where Reflection just can't do some things.Using a modopt instead of attribute would have been a much better choice.
Daniel
2010-07-18 22:07:09
@Daniel: You can disable the use of the `dynamic` keyword on a project level, which is a good thing to do for most C# projects IMO.
Steven
2010-07-18 22:25:01
Daniel: There are already things Reflection can't do, like emulate Perl's `wantarray`, which can tell you what type the caller expects you to return.
Gabe
2010-07-19 05:38:54
+2
A:
You do this by checking if an instance is of type IDynamicMetaObjectProvider
or you can check whether the type implements IDynamicMetaObjectProvider
.
Steven
2010-07-18 22:19:54
This only works if you have an object instance. typeof(T).GetInterfaces() returns a 0-length array.
Dmitry
2010-07-18 23:02:48
This checks if an instance is a dynamic object, but the OP wants to know if the type parameter of the class was set to dynamic.
Dan Bryant
2010-07-18 23:06:16
There are no dynamic objects: all objects can be referenced via `dynamic`.
Steven Sudit
2010-07-19 01:14:17