2

Suppose I have this class:

class MyClass {
  public int MyProperty { get; set; }
}

And I want to get the MyProperty as string (e.g. "MyProperty") but through lambda expression or any other way that is "refactoring-friendly".

Is there a syntax that is something like this:

void BindToDataSource(IEnumerable<MyClass> list) {
    myComboBox.DataSource = list;
    myComboBox.DisplayMember = typeof(MyClass).GetPropertyToString(c => c.MyProperty);
}

I dont want to this code:

myComboBox.DisplayMember = "MyProperty"

because it is not "refactoring-friendly".

3

1 Answer 1

6

Take a look at the answer to this: Workaround for lack of 'nameof' operator in C# for type-safe databinding?

In your case, if you implement this Generic Class:

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;
    }
}

You can use it like this:

void BindToDataSource(IEnumerable<MyClass> list) 
{
    myComboBox.DataSource = list;
    myComboBox.DisplayMember = Nameof<MyClass>.Property(e => e.MyProperty);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.