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

rajeemcariazo
  • 2,476
  • 5
  • 36
  • 62
  • So you want to use reflection to avoid using reflection? There is no compile-time reflection: http://blogs.msdn.com/b/ericlippert/archive/2009/05/21/in-foof-we-trust-a-dialogue.aspx – Tim Schmelter May 22 '13 at 10:43
  • I don't mind if it is using reflection, I just want my code to be "refactoring-friendly." – rajeemcariazo May 22 '13 at 10:44
  • possible duplicate of [Compile Time Reflection in C#](http://stackoverflow.com/questions/9335126/compile-time-reflection-in-c-sharp) – Tim Schmelter May 22 '13 at 10:45

1 Answers1

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);
}
Community
  • 1
  • 1
greg84
  • 7,541
  • 3
  • 36
  • 45