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

1

3

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."?
Vaccaro answered 21/5, 2010 at 16:21 Comment(4)
I think that's not possible, but since I'm not completely sure, I'll just wait and see what answers come in. ;)Immemorial
Out of curiosity, why do you want to know?Tiffanytiffi
Hi Eric, I thought your comment was directed at Lucero. But I suspect now that it was directed towards my original question. I've sent you a private email at your official email address with the answer to your question.Vaccaro
See this too: is-there-a-way-to-test-if-a-variable-is-dynamicCedell
T
3

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.

Tiffanytiffi answered 21/5, 2010 at 16:27 Comment(2)
What is the attribute on methods returning a dynamic type? I see "DynamicAttribute" on a field or property with a dynamic type, but this attribute does not appear on a method returning 'dynamic' when I reflect on it (at least, not in my test case)??Epencephalon
An example of this not working for methods is here: #8440286Epencephalon

© 2022 - 2024 — McMap. All rights reserved.