1

From Stackoverflow, I've picked up some useful code to remove magic strings from my application. The code looks like this:

protected void OnPropertyChanged<T>(Expression<Func<T>> selectorExpression) { }

The method is called by:

this.OnPropertyChanged( () => DisplayName);

(Where DisplayName is a property of the class.)

Using methods of this form is really useful (I like how it is easy to refactor) but I don't really understand what is is doing.

Where is T assigned, and what value does it take? How does intellisense pick up which properties the class has (is T implicitly set from the context in which the method is called?)

Is the () => DisplayName expression fixed at compile time, or is it calculated each time the method is called? Related: is using magic strings more efficient?

Oliver
  • 11,297
  • 18
  • 71
  • 121

2 Answers2

1

Check this question: Retrieving Property name from lambda expression. This is possible thanks to expression that can be analyzed at runtime and it is possible to get property name from it.

You should also read this question: Difference between Expression<Func<>> and Func<>.

The bottom line is that the Expression is code that could not only be executed but also analyzed at runtime as an expression tree.

Community
  • 1
  • 1
empi
  • 15,755
  • 8
  • 62
  • 78
1

The Expression class is typically used for writing dynamic code that can be changed at runtime. T is the type returned by your lambda. It can be any type.

From MSDN: Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y. http://msdn.microsoft.com/en-us/library/bb397951.aspx

Expression trees can then be compiled or analysed at runtime.

Expression<Func<T>> selectorExpression

is the type for an expression that is a function with no arguments returning a type T.

You could compile and run selectorExpression at runtime.

In the case of your OnPropertyChanged method selectorExpression isn't compiled and executed it is just analysed to retrieve the property name. This post goes into a bit of detail on how it works: Retrieving Property name from lambda expression

There is a performance overhead in doing this though in my opinion it is negligible for an OnPropertyChanged handler. The benefits of easy refactoring greatly outweigh the performance cost.

Community
  • 1
  • 1
Jared Kells
  • 6,771
  • 4
  • 38
  • 43