Getting the name of a property in c#

You do it like this, using compiler generated expression trees:

public static string GetMemberName<T, TValue>(Expression<Func<T, TValue>> memberAccess)
{
    return ((MemberExpression)memberAccess.Body).Member.Name;
}

Now call the static method from code:

class MyClass
{
    public int Field;
    public string Property { get; set; }
}

var fieldName = GetMemberName((MyClass c) => c.Field);
var propertyName = GetMemberName((MyClass c) => c.Property);
// fieldName has string value of `Field`
// propertyName has string value of `Property`

You can now also use refactoring to rename that field without breaking this code


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


With C# 6.0, you can use the new nameof operator.

nameof(MyClass.MyField)  // returns "MyField"
nameof(MyClass)  //returns "MyClass"

See nameof (C# and Visual Basic Reference) for more examples.

Tags:

C#

Reflection