Water Cooler v2
Water Cooler v2

Reputation: 33880

Reflect on a dynamic type to tell if it was a dynamic type, to begin with

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."?

Upvotes: 3

Views: 419

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660455

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.

Upvotes: 3

Related Questions