.NET – How to Get Class Property Name Using Reflection

.netreflection

I have my winform application gathering data using databinding. Everything looks fine except that I have to link the property with the textedit using a string:

Me.TextEdit4.DataBindings.Add(New System.Windows.Forms.Binding("EditValue", Me.MyClassBindingSource, "MyClassProperty", True))

This works fine but if I change the class' property name, the compiler obviously will not warn me .

I would like to be able to get the property name by reflection but I don't know how to specify the name of the property I want (I only know how to iterate among all the properties of the class)

Any idea?

Best Answer

If you are using C# 3.0, there is a way to get the name of the property dynamically, without hard coded it.

private string GetPropertyName<TValue>(Expression<Func<BindingSourceType, TValue>> propertySelector)
{
    var memberExpression = propertySelector.Body as MemberExpression;
    return memberExpression != null 
           ? memberExpression.Member.Name 
           : string.empty;
}

Where BindingSourceType is the class name of your datasource object instance.

Then, you could use a lambda expression to select the property you want to bind, in a strongly typed manner :

this.textBox.DataBindings.Add(GetPropertyName(o => o.MyClassProperty),
                              this.myDataSourceObject,
                              "Text");

It will allow you to refactor your code safely, without braking all your databinding stuff. But using expression trees is the same as using reflection, in terms of performance.

The previous code is quite ugly and unchecked, but you get the idea.

Related Question