views:

36

answers:

1

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);
+3  A: 

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

Darin Dimitrov
Is there a workaround to detect anonymous types anyway?
JacobE
@JacobE: I think all anonymous types currently contains 'AnonymousType' in the typename.
leppie