tags:

views:

132

answers:

4

Say, for example, I've got this simple class:

public class MyClass
{
  public String MyProperty { get; set; }
}

The way to get the PropertyInfo for MyProperty would be:

typeof(MyClass).GetProperty("MyProperty");

This sucks!

Why? Easy: it will break as soon as I change the Name of the Property, it needs a lot of dedicated tests to find every location where a property is used like this, refactoring and usage trees are unable to find these kinds of access.

Ain't there any way to properly access a property? Something, that is validated on compile time?
I'd love a command like this:

propertyof(MyClass.MyProperty);
A: 

You could write a wrapper class: MyClassReflector, which would keep the reflection code in one place rather than spreading it out over your code. Also a tool like Reflector will notice if you change the name of the property (if you use it's rename refactoring). It will search for string literals that may refer to the property name, and allow you to update them.

chibacity
+1  A: 

The whole point of reflection is to be able to access stuff at runtime. If we assume your operator would work, you already have the class information and thus the property, making the whole thing completely useless.

Femaref
I already have the property? Without the name in text? How that??
Sam
+3  A: 

The closest you can come at the moment is to use an expression tree:

GetProperty<MyClass>(x => x.MyProperty)

and then suck the PropertyInfo out in GetProperty (which you'd have to write). However, that's somewhat brittle - there's no compile-time guarantee that the expression tree is only a property access.

Another alternative is to keep the property names that you're using somewhere that can be unit tested easily, and rely on that.

Basically what you want is the mythical infoof operator which has been talked about many times by the C# team - but which hasn't made the cut thus far :(

Jon Skeet
Looks intriguing - but how would I write GetProperty? I'm not even sure *what* it is - a generic class? Or just a generic method?infoof sounds lovely, too bad it's not in (yet).
Sam
+2  A: 

The Caliburn project has a good implementation of what you are looking for to take care of INotifyPropertyChanged property names. You can adapt the expression code to what you need to do. Take a look at the Caliburn.Core.PropertyChangedBase class.

Garo Yeriazarian
Interesting! This helps me understand Jon Skeets answer.
Sam