Question

Workaround for lack of 'nameof' operator in C# for type-safe databinding?

There has been a lot of sentiment to include a nameof operator in C#. As an example of how this operator would work, nameof(Customer.Name) would return the string "Name".

I have a domain object. And I have to bind it. And I need names of properties as strings then. And I want them to be type-safe.

I remember coming across a workaround in .NET 3.5 which provided the functionality of nameof and involved lambda expressions. However, I have not been able to locate this workaround. Can anyone provide that workaround to me?

I am also interested in a way to implement the functionality of nameof in .NET 2.0 if that is possible.

 45  26578  45
1 Jan 1970

Solution

 78

This code basically does that:

class Program
{
    static void Main()
    {
        var propName = Nameof<SampleClass>.Property(e => e.Name);

        Console.WriteLine(propName);
    }
}

public class Nameof<T>
{
    public static string Property<TProp>(Expression<Func<T, TProp>> expression)
    {
        var body = expression.Body as MemberExpression;
        if(body == null)
            throw new ArgumentException("'expression' should be a member expression");
        return body.Member.Name;
    }
}

(Of course it is 3.5 code...)

2008-11-19

Solution

 6

While reshefm and Jon Skeet show the proper way to do this using expressions, it should be worth noting there's a cheaper way to do this for method names:

Wrap a delegate around your method, get the MethodInfo, and you're good to go. Here's an example:

private void FuncPoo()
{
}

...

// Get the name of the function
string funcName = new Action(FuncPoo).Method.Name;

Unfortunately, this works only for methods; it does not work for properties, as you cannot have delegates to property getter or setter methods. (Seems like a silly limitation, IMO.)

2008-11-19