Tutorial :C# Detecting AnonymousType new{name=value,} and convert into Dictionary


I need to detect if an object was created anonymously like new{name=value,}

if it is an AnonymousType, it should add it's properties names/values into a


This is what I hacked together myself:

var name="name";    var obj = new { name = new object(), };    var lookup = new Dictionary<string,object>();      if(obj.GetType().Name.StartsWith("<>f__AnonymousType"))  {      foreach (var property in obj.GetType().GetProperties())      {          lookup[property.Name] = property.GetValue(obj, null);      }  }  else  {      lookup[name]=obj;  }  

I was wondering if there is a better/faster way of detecting AnonymousTypes, or if there is a better/faster way to dump an object's properties names/values into a



To get all the properties of an object, with its values into a Dictionary, you can couple the power of Linq to Objects with Reflection.

You can use the Enumerable.ToDictionary method:

var dic = obj.GetType()               .GetProperties()               .ToDictionary(p => p.Name,  p=> p.GetValue(obj, null));  

This will return you a Dictionary<string, object>.


Use the new collection object initializer syntax instead of an anonymous type:

var obj = new Dictionary<string, object>()  {      { "Name", t.Name },      { "Value", t.Value }  };  


Detecting an anonymous type is a little hard; not-least it depends on the language! VB anon-types don't look the same as C# anon-types. I'd be dubious about logic that acts vary differently on anon-types. You might check for [CompilerGenerated], but note that it doesn't just mean "anonymous type" - there are others that do this.

Personally, I wouldn't distinguish in this scenario.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »