views:

121

answers:

2

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

+3  A: 

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>
{
...
}
Catalin DICU
+11  A: 

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 & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
}

HTH.

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

Sunny