C# – Get Property Name Using Reflection

c++reflection

Given this class:

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

How will I be able to extract the name of MyProperty in code?

For example, I am able to get the name of the class like this

typeof(MyClass).Name

How can I do something similar for the property?

The reason for the question is that I want this particular code to be resistant against refactorizations of the names.

EDIT: With resistant I mean that I want the code at the call site to be robust in the face of changes of the propertyname. I have some stuff that is using a string representation of the property name. Sorry for the poor phrasing.
I did not include call site code in order to keep the problem clean and not wander off into other discussions on the nature of the call site code.

Best Answer

In C# 6 we can do it very simply

nameof(MyField);

you can get method\type\propery\field\class\namespace names in the same way ex

 nameof(MyClass);
 nameof(namespacename1)  // returns "namespacename1"
 nameof(TestEnum.FirstValue) // returns enum's first value

MSDN Reference

Look at this post