How To Test if a Type is Anonymous?

C#ReflectionAnonymous Types

C# Problem Overview


I have the following method which serialises an object to a HTML tag. I only want to do this though if the type isn't Anonymous.

private void MergeTypeDataToTag(object typeData)
{
    if (typeData != null)
    {
        Type elementType = typeData.GetType();

        if (/* elementType != AnonymousType */)
        {
            _tag.Attributes.Add("class", elementType.Name);    
        }

        // do some more stuff
    }
}

Can somebody show me how to achieve this?

Thanks

C# Solutions


Solution 1 - C#

From http://www.liensberger.it/web/blog/?p=191:

private static bool CheckIfAnonymousType(Type type)
{
    if (type == null)
        throw new ArgumentNullException("type");
    
    // HACK: The only way to detect anonymous types right now.
    return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
        && type.IsGenericType && type.Name.Contains("AnonymousType")
        && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
        && type.Attributes.HasFlag(TypeAttributes.NotPublic);
}

EDIT:
Another link with extension method: https://stackoverflow.com/questions/1650681/determining-whether-a-type-is-an-anonymous-type

Solution 2 - C#

Quick and dirty:

if(obj.GetType().Name.Contains("AnonymousType"))

Solution 3 - C#

You can just check if the namespace is null.

public static bool IsAnonymousType(this object instance)
{
        
    if (instance==null)
        return false;
    
    return instance.GetType().Namespace == null;
}

Solution 4 - C#

Well, today compiier generates anonymous types as generic AND sealed classes. A paradoxal combination since specialization of a generic class is a kind of inheritance, isn't? So you can check for this:

  1. Is this a generic type? Yes => 2) is its definition sealed && not public? Yes => 3) is its definition has CompilerGeneratedAttribute attribute? I guess, if these 3 criteria are true together, we have an anonymous type... Well... There is a problem with ANY of methods described - they are use aspects that may change in next versions of .NET and it will be so until Microsoft will add IsAnonymous boolean property to Type class. Hope it will happen before we all die... Until that day, it can be checked like so:

    using System.Runtime.CompilerServices; using System.Reflection;

    public static class AnonymousTypesSupport { public static bool IsAnonymous(this Type type) { if (type.IsGenericType) { var d = type.GetGenericTypeDefinition(); if (d.IsClass && d.IsSealed && d.Attributes.HasFlag(TypeAttributes.NotPublic)) { var attributes = d.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false); if (attributes != null && attributes.Length > 0) { //WOW! We have an anonymous type!!! return true; } } } return false; }

     public static bool IsAnonymousType<T>(this T instance)
     {
         return IsAnonymous(instance.GetType());
     }
    

    }

Solution 5 - C#

Check for CompilerGeneratedAttribute and DebuggerDisplayAttribute.Type

here is the code generated by the compiler for an anomymous type

[CompilerGenerated, DebuggerDisplay(@"\{ a = {a} }", Type="<Anonymous Type>")]
internal sealed class <>f__AnonymousType0<<a>j__TPar>
{
...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaveDevView Question on Stackoverflow
Solution 1 - C#SunnyView Answer on Stackoverflow
Solution 2 - C#BjarkeCKView Answer on Stackoverflow
Solution 3 - C#DalSoftView Answer on Stackoverflow
Solution 4 - C#Konstantin IsaevView Answer on Stackoverflow
Solution 5 - C#Catalin DICUView Answer on Stackoverflow