Turn Anonymous Types into IDictionary of values

By Roy Osherove In General Software Devel...

Markdown version

Historical article · Originally published March 11, 2008; technical details may be outdated.

Hers is one cool use I found for Anonymous Types (stolen from the ASP.NET MVC Framework): Use anonymous types to create and initialize a list of dictionary values which you can pass around:

void CreateADictionaryFromAnonymousType()
       {
           var dictionary = MakeDictionary(new {Name="Roy",Country="Israel"});
           Console.WriteLine(dictionary["Name"]);
       }

private IDictionary MakeDictionary(object withProperties)
       {
           IDictionary dic = new Dictionary<string, object>();
           var properties = System.ComponentModel.TypeDescriptor.GetProperties(withProperties);
           foreach (PropertyDescriptor property in properties)
           {
               dic.Add(property.Name,property.GetValue(withProperties));
           }
           return dic;
       }

More in General Software Devel...

All posts in General Software Devel...