Determining whether a Type is an Anonymous Type

xyz picture xyz · Oct 30, 2009 · Viewed 7.2k times · Source

In C# 3.0, is it possible to determine whether an instance of Type represents an Anonymous Type?

Answer

Even though an anonymous type is an ordinary type, you can use some heuristics:

public static class TypeExtension {

    public static Boolean IsAnonymousType(this Type type) {
        Boolean hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Count() > 0;
        Boolean nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
        Boolean isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;

        return isAnonymousType;
    }
}

Another good heuristic to be used is if the class name is a valid C# name (anonymous type are generated with no valid C# class names - use regular expression for this).