This question already has an answer here:
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
From: http://www.liensberger.it/web/blog/?p=191
HTH.
EDIT:
Another link with extension method: Determining whether a Type is an Anonymous Type
Check for
CompilerGeneratedAttribute
andDebuggerDisplayAttribute.Type
here is the code generated by the compiler for an anomymous type
Quick and dirty:
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:
You can just check if the namespace is null.