.Net Get property name

Do you mean a property, or do you mean a field?

There are clever lambda techniques for getting the names of properties - here's a C# example:

String GetPropertyName<TValue>(Expression<Func<TValue>> propertyId)
{
   return ((MemberExpression)propertyId.Body).Member.Name;
}

Call it like this:

GetPropertyName(() => MyProperty)

and it will return "MyProperty"

Not sure if that's what you're after or not.


public static PropertyInfo GetPropInfo<T>(this T @object
    , Expression<Action<T>> propSelector)
{
    MemberExpression exp= propSelector.Body as MemberExpression;
    return exp.Member as PropertyInfo;
}

Then use it like this:

string str = ....
string propertyName = str.GetPropInfo(a => a.Length).Name;

Note that the above method is an extension and should be written in a static class and used by including the namespace


If you are using C# 6.0 (not released when this question was asked) you can use the following:

nameof(PropertyName)

This is evaluated at compile time and is converted to a string, the nice thing about using nameof() is that you don't have to manually change a string when you refactor. (nameof works on more than Properties, CallerMemberName is more restrictive)

If you are still stuck in pre c# 6.0 then you can use CallerMemberNameAttribute (it requires .net 4.5)

private static string Get([System.Runtime.CompilerServices.CallerMemberName] string name = "")
{
    if (string.IsNullOrEmpty(name))
        throw new ArgumentNullException("name");
    return name;
}

Tags:

.Net