Roy Osherove

View Original

Turn Anonymous Types into IDictionary of values

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;
       }