Tutorial :How to detect an anonymous object with .NET Reflection? [duplicate]


Possible Duplicates:
How To Test if a Type is Anonymous?
Anonymous Types - Are there any distingushing characteristics?

Is there a way to detect if a Type object refers to an anonymous object?

var obj = new { A = "Hello" };  Type x = obj.GetType();  // is there something equivalent to x.IsAnonymous?  Assert.IsTrue(x.IsAnonymous);  


No, there is no way because anonymous types are just a compile time artifact, at runtime they are just regular types emitted by the compiler. As they are compiler generated those types are marked with the CompilerGeneratedAttribute which could be used to determine if this is the case.

var obj = new { A = "Hello" };  var isAnonTypeCandidate = obj      .GetType()      .GetCustomAttributes(typeof(CompilerGeneratedAttribute), true)      .Count() > 0;  

Of course that will return true also for types that were decorated with this attribute so it's not 100% guarantee that it is an anonymous type

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »