Search The Blog
About this site

@RoyOsherove

Subscribe!

This site aims to connect all the dots of my online activities - from tools, books blogs and twitter accounts, to upcoming conferences, engagements and user group talks.

from 5whys.com
Twitter: @RoyOsherove
My Book: The Art of Unit Testing
Latest Posts
« Belgium TechDays Slides and demos, and my travel schedule | Main | Want a Wii? (And learn about Typemock Isolator?) »
Tuesday
Mar112008

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

PrintView Printer Friendly Version

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>