Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Test if a Type is Anonymous? [duplicate]

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

like image 752
DaveDev Avatar asked Mar 20 '10 12:03

DaveDev


2 Answers

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: Determining whether a Type is an Anonymous Type

like image 175
Sunny Avatar answered Sep 21 '22 10:09

Sunny


Quick and dirty:

if(obj.GetType().Name.Contains("AnonymousType")) 
like image 33
BjarkeCK Avatar answered Sep 20 '22 10:09

BjarkeCK