Monday, January 28, 2013

Convert an object’s property values to a dictionary of string,object

Here is a simple helper function that converts any class object to a dictionary of string,object, where the key is the PropertyName:

public static class ReflectionHelper
{
    public static IDictionary<string, object> ToDictionary<TModel>(this TModel model)
   {
       BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
       Dictionary<string, object> dictionary = new Dictionary<string, object>();

       foreach (PropertyInfo property in model.GetType().GetProperties(publicAttributes))
       {
           if (property.CanRead)
               dictionary.Add(property.Name, property.GetValue(model, null));
       }

       return dictionary;
   }
}

public class Test
{
    public string Name{get;set;}
}

void Main()
{
    Test t = new Test{Name = "Raj Rao"};
    foreach(var v in t.ToDictionary())
    {
           Console.WriteLine(v.Key + ":" + v.Value);
    }

}

The output will be:

Name: Raj Rao

This again was inspired by some of the Helper functions available in Asp.Net’s MVC HTML helper class.

Getting rid of magic strings that point at PropertyNames

Often times, you end up with code that includes magic strings that point at property names of a class. I hate this, because it normally ends up causing runtime errors instead of compile time errors.

While working with Asp.Net MVC, I found that you could pass properties to helper methods (such as Html.TextBoxFor) and it would automagically figure out the name of the property and use it to build out the ID and Name fields of the html object. I wanted something similar to that and here is my code:

//The helper class that provides the “GetPropertyName” method
public static class ReflectionHelper
{
    public static string GetPropertyName<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> expression)
    {
        MemberExpression body = (MemberExpression) expression.Body;
        return body.Member.Name;
    }
}

//A test class to test what we are doing
public class Test
{
    public string Name{get;set;}
}

//A simple test
void Main()
{
    Test t = new Test();
    Console.WriteLine(t.GetPropertyName(m => m.Name));
}