Tag Archives: RX

Get compile time support for Property names


Many times we need to use string values for C# properties. Although this is not a common practise, we may not have choice sometimes e.g. using RX –

 .Where(e => e.EventArgs.PropertyName == "SearchString")
 .Subscribe(_ => DoSomeWork());

In this case,  we have to pass the string value (name) of the property for RX Observable to work. I am interested in subscribing to this event of my property(which is in turn bound to textbox on view).

So I can either pass the string literal which provides no compile time support or I can use expression trees to pass an expression and retrieve string name literal at runtime as follows:

 .Where(e => e.EventArgs.PropertyName == GetPropertyName(() => SearchString))
 .Subscribe(_ => DoSomeWork());

This works because I have written a private function in my class to extract the actual string name from the propertyname. The function is as follows:

public static string GetPropertyName<T>(Expression<Func<T>> expression)
    MemberExpression memberExpression = (MemberExpression)expression.Body;
    return memberExpression.Member.Name;

Have a nice day!