2010-08-04

Get the name of a property as a string in C#

Another developer showed me something very useful with Expression Trees in C# (thanks, Pierre! Full credit goes to you). To show you the awesomeness of it all, let's start with a class called Person.


public class Person
{
public string Name { get; set; }
public string Email { get; set; }
}


Now let's say I have an instance of Person


var person = new Person
{
Name = "mark kockerbeck",
Email = "noneofyourbusiness@face.com",
};


Imagine creating a Dictionary<string,string> of this particular Person's properties (e.g. "Name" and "Email") and the corresponding property values.

We could easily do something like the following:


var dictionary = new Dictionary<string, string>
{
{ "Name", person.Name },
{ "Email", person.Email },
};


But there is unnecessary redundancy and repetition in this. We have to say the property twice (and as a messy string no less!).

Well, we could use reflection...


var dictionary = new Dictionary<string, string>();
typeof(Person).GetProperties().ToList().ForEach(p => dictionary.Add(p.Name, p.GetValue(person, null).ToString()));


...but a lot of developers seem scared by Reflection & especially a concise statement like the above.

Below is a way to get the Property name & value in one small statement while keeping a strong typed non-reflective code base.

We just need to create a new Method...

public static void AddField<T>(Dictionary<string,T> dictionary, Expression<Func<T>> expression)
{
var name = ((MemberExpression)expression.Body).Member.Name;
dictionary.Add(name, expression.Compile()());
}


And now just call each property as a Func<T>...


var dictionary = new Dictionary<string, string>();
AddField(dictionary, () => person.Name);
AddField(dictionary, () => person.Email);


Personally, I like the reflective way but I thought this was a very good use case for an Expression Tree

No comments: