Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get PropertyInfo from property instead of name

Tags:

c#

reflection

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);
like image 733
Sam Avatar asked Jun 08 '10 12:06

Sam


People also ask

How do I find information on a property?

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.

How to get propertyname c#?

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.


2 Answers

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 :(

like image 181
Jon Skeet Avatar answered Oct 26 '22 18:10

Jon Skeet


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).

like image 31
Profesor Caos Avatar answered Oct 26 '22 16:10

Profesor Caos