views:

88

answers:

1

Is there a way that one can tell if the type that an object was assigned to, was a dynamic type?

For example:

dynamic foo = GetCat();

Console.WriteLine( (foo is Cat).ToString() ); // will print True because
// at the execution time, foo will have assumed the Cat type. However, is
// there a mechanism by which I can reflect on foo and say, "This guy was assigned
// a dynamic type, to begin with."?
+3  A: 

Is there a way that one can tell if the type that an object was assigned to was a dynamic type?

Nope, not if foo is a local variable.

"dynamic" is a compile-time feature. It's just a hint to the compiler that means "don't bother to try to do type analysis at compile time on this expression; instead, generate code that invokes a special version of the compiler at runtime".

At runtime, the local variable foo is just a local variable of type object, and the contents of the local variable are a reference to a Cat. The fact that the compiler knew that the author of the code wanted to avoid type analysis on foo at compile time has been lost.

It is possible to figure out whether a method that returns object is actually returning dynamic, by examining the compiler-generated attributes on the method using reflection.

Eric Lippert
Many thanks, Eric. Many thanks.
Water Cooler v2