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);
Alternatively, go to the local Tax Assessor's office and give them the owner's name or property address. Property deeds are often available online. Try searching for “Recorder of Deeds,” with the name of the county. Or, go to the county or city office and ask where you can access physical records of property deeds.
To get names of properties for a specific type use method Type. GetProperties. Method returns array of PropertyInfo objects and the property names are available through PropertyInfo.Name property.
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 :(
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With