Workaround for Lack of 'Nameof' Operator in C# for Type-Safe Databinding

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

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...)

Adding nameof to C# through backdoors

Doing any pre-compilation code changes would be an extreme hassle. So I would avoid it.

I wouldn't worry too much about performance - most times when you need a property name as a string you'll end up doing reflection or IO anyway, so performance is going to be relatively slow anyway.

Here's what I suggest to use:

public static string ToPropertyName<T>(this Expression<Func<T>> @this)
{
var @return = string.Empty;
if (@this != null)
{
var memberExpression = @this.Body as MemberExpression;
if (memberExpression != null)
{
@return = memberExpression.Member.Name;
}
}
return @return;
}

Now you can do this:

Expression<Func<T>> px = x => x.Foo;
var pn = px.ToPropertyName(); // == "Foo"

Trying to find a way to get the field names of class

You can use reflection to get properties or fields of a type:

var properties = typeof(Person)
.GetProperties()
.Select(p => p.Name)
.ToList();

Get property name from class

There is a very neat solution here: Workaround for lack of 'nameof' operator in C# for type-safe databinding?

Can I write the method name without using a String to pass the name of the method? (c#)

If you can use C#6, you have the nameof operator, which does just that.

string propertyName = nameof(foo.Val);

If you use C# 5, you can leverage expression trees:

public static string GetPropertyName<TParent>(Expression<Func<TParent, object>> prop)
{
var expr = prop.Body;

if (expr.NodeType == ExpressionType.Convert)
expr = ((UnaryExpression)expr).Operand;

if (expr.NodeType == ExpressionType.MemberAccess)
return ((MemberExpression)expr).Member.Name;

throw new ArgumentException("Invalid lambda", "prop");
}

Use this helper function like this (assuming it's in a ReflectionHelper class):

string propertyName = ReflectionHelper.GetPropertyName<foo>(x => x.Val);

This way, you can safely use refactorings in your IDE.



Related Topics



Leave a reply



Submit