C# – Referring to the property itself in C#. Reflection? Generic? Type

cpropertiesreflection

Please bear with me if this question isn't well formulated. Not knowing is part of the problem.

An example of what I'd like to accomplish can be found in PropertyChangedEventArgs in WPF. If you want to flag that a property has changed in WPF, you do it like this:

PropertyChanged(this, new PropertyChangedEventArgs("propertyName"));

You pass a string to PropertyChangedEventArgs that refers to the property name that changed.

You can imagine that I don't really want hard coded strings for property names all over my code. Refactor-rename misses it, of course, which makes it not only aesthetically unappealing but error prone as well.

I'd much rather refer to the property itself … somehow.

PropertyChanged(this, new PropertyChangedEventArgs(?SomeClass.PropertyName?));

It seems like I should be able to wrap this in a short method that lets me say something like the above.

private void MyPropertyChanged(??) {
  PropertyChanged(this, new PropertyChangedEventArgs(??.ToString()??));
}

... so I can say something like:
MyPropertyChanged(Person.Name); //where I'm interested in the property *itself*

So far I'm drawing a blank.

Best Answer

There isn't a direct way to do this, unfortunately; however, you can do it in .NET 3.5 via Expression. See here for more. To copy the example:

PropertyInfo prop = PropertyHelper<Foo>.GetProperty(x => x.Bar);

(it is pretty simple to change that to return the name instead of the PropertyInfo).

Likewise, it would be pretty simple to write a variant:

OnPropertyChanged(x=>x.Name);

using:

OnPropertyChanged<T>(Expression<Func<MyType,T>> property) {...}