nameof expression in .net framework 4

MSL picture MSL · Jul 7, 2015 · Viewed 28.7k times · Source

"nameof" expression is introduced in Visual Studio 2015 and c# 6

nameof (C# and Visual Basic Reference)

How can u use it or write a similar method in older versions like .net framework 4.

Answer

Rob picture Rob · Jul 7, 2015

If you're talking about an equivalent for C# before C#6, this will get the job done (in a hacky way) for properties. It can probably be expanded upon to include fields, methods, etc.

public static class TestExtension
{
    public static String nameof<T, TT>(this T obj, Expression<Func<T, TT>> propertyAccessor)
    {
        if (propertyAccessor.Body.NodeType == ExpressionType.MemberAccess)
        {
            var memberExpression = propertyAccessor.Body as MemberExpression;
            if (memberExpression == null)
                return null;
            return memberExpression.Member.Name;
        }
        return null;
    }
}

Just whipped this up quickly, so there's a lot to be improved, but you use it like this:

public class myClass
{
    public string myProp { get; set; }
}

var a = new myClass();
var result = a.nameof(b => b.myProp);

Result contains 'myProp'

Update:

More comprehensive (though still not that pretty)

public static class TestExtension
{
    public static String nameof<T, TT>(this Expression<Func<T, TT>> accessor)
    {
        return nameof(accessor.Body);
    }

    public static String nameof<T>(this Expression<Func<T>> accessor)
    {
        return nameof(accessor.Body);
    }

    public static String nameof<T, TT>(this T obj, Expression<Func<T, TT>> propertyAccessor)
    {
        return nameof(propertyAccessor.Body);
    }

    private static String nameof(Expression expression)
    {
        if (expression.NodeType == ExpressionType.MemberAccess)
        {
            var memberExpression = expression as MemberExpression;
            if (memberExpression == null)
                return null;
            return memberExpression.Member.Name;
        }
        return null;
    }
}

Accessing static properties/fields:

TestExtension.nameof(() => myClass.MyOtherField)

Accessing parameters within functions:

void func (int a) {
    TestExtension.nameof(() => a);
}