tenpn tenpn - 19 minutes ago 2
C# Question

How to get the PropertyInfo of a specific property?

I want to get the PropertyInfo for a specific property. I could use:

foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
if ( p.Name == "MyProperty") { return p }
}


But there must be a way to do something similar to

typeof(MyProperty) as PropertyInfo


Is there? Or am I stuck doing a type-unsafe string comparison?

Cheers.

Answer

You can use the new nameof() operator that is part of C# 6 and available in Visual Studio 2015. More info here.

For your example you would use:

PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));

The compiler will convert nameof(MyObject.MyProperty) to the string "MyProperty" but you gain the benefit of being able to refactor the property name without having to remember to change the string because Visual Studio, ReSharper, and the like know how to refactor nameof() values.