Reputation: 29009
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);
Upvotes: 14
Views: 3440
Reputation: 193
In the time since this question was posted, C# 6 has been released with the nameof operator. This allows a property to be accessed with the following
PropertyInfo myPropertyInfo = typeof(MyClass).GetProperty(nameof(MyClass.MyProperty));
If you rename the property, this code will not compile (actually it will, since the rename will change this line of code as well if the rename is done properly).
Upvotes: 3
Reputation: 1503140
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 :(
Upvotes: 6
Reputation: 61497
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.
Upvotes: -2