A few answers that might be useful. In C# 3.0 anonymous types are immutable indeed; there are only getters while the properties can only be set through the constructor (which is created by the compiler). In VB 9.0 anonymous types are mutable except
for fields marked with the Key keyword. This is the addition Paul Vick was referring to.
Concerning detection of anonymous types, you're right there's no metadata available that ensures a type is a dynamically cooked up type, neither is there an API to help you out (which wouldn't give any guarantuees anyhow if there's no dedicated piece of metadata). A good heuristic to determine anonymous types is:
- Check for the CompilerGeneratedAttribute using reflection
- Type name contains "AnonymousType"
- Type name starts with either "<>" or "VB$" (these prefixes cannot be used by code written by a developer)
- Type is generic
- Type definition is private (and sealed in C# 3.0)
The code below illustrates this:
static TypeAttributes s_ta = TypeAttributes.NotPublic;
static bool IsAnonymousType(Type t)
return t.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Length == 1
&& (t.Name.StartsWith("<>") || t.Name.StartsWith("VB$"))
&& (t.Attributes & s_ta) == s_ta;
An alternative is to construct a regex to check the name to be valid against C# 3.0 or VB 9.0 anonymous type naming conventions - which unfortunately aren't official by any means.