Getting the name of a property as a string

EDIT

Everything below is completely unnecessary in C#6, just use the nameof operator
So instead of using any of the shenanigans and hacks below, simply write

 SelectList list = new SelectList(items, nameof(Id), nameof(Text));

Simples.

Original article below for C#5 and under...

There are many times when it is necessary to specify the name of which property you want to read from.

For instance, when creating a SelectList from a list of objects you must specify the data value and data text fields like so

 SelectList list = new SelectList(items, "Id", "Text");

This approach is not ideal as the values are hardcoded and any refactoring will involve changing these values manually (not counting the use of Resharper or similar). We can use reflection to determine the name of a property of a given type.

Using these we can take a more programmatic approach that will be refactoring-safe.

public static string GetPropertyName<T>(this T type, Expression<Func<T, object>> expression)
{
    return GetPropertyName<T>(expression);
}

public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
    var lambda = expression as LambdaExpression;

    MemberExpression memberExpression = lambda.Body is UnaryExpression
        ? (lambda.Body as UnaryExpression).Operand as MemberExpression
        : lambda.Body as MemberExpression;

    return memberExpression == null
        ? null
        : (memberExpression.Member as PropertyInfo).Name;
}

This means we can create a SelectList where the values for the text and value fields will automatically change if the underlying type is refactored.

List<ListItem> items = GetItemsForDropdown();

var item = items.FirstOrDefault();
var idName = item.GetPropertyName(i => i.ID);
var valueName = item.GetPropertyName(i => i.Value);

SelectList list = new SelectList(items, idName, valueName);

The code used above can be found at BitBucket and comments below are welcome


Share Tweet Send
0 Comments
Loading...
You've successfully subscribed to SimonReynolds.ie
Great! Next, complete checkout for full access to SimonReynolds.ie
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.