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());
}
}