Getting Object Property to String Using Lambda Expression in C# -
suppose have class:
class myclass { public int myproperty { get; set; } }
and want myproperty string (e.g. "myproperty") through lambda expression or other way "refactoring-friendly".
is there syntax this:
void bindtodatasource(ienumerable<myclass> list) { mycombobox.datasource = list; mycombobox.displaymember = typeof(myclass).getpropertytostring(c => c.myproperty); }
i dont want code:
mycombobox.displaymember = "myproperty"
because not "refactoring-friendly".
take @ answer this: workaround lack of 'nameof' operator in c# type-safe databinding?
in case, if implement generic class:
public class nameof<t> { public static string property<tprop>(expression<func<t, tprop>> expression) { var body = expression.body memberexpression; if(body == null) throw new argumentexception("'expression' should member expression"); return body.member.name; } }
you can use this:
void bindtodatasource(ienumerable<myclass> list) { mycombobox.datasource = list; mycombobox.displaymember = nameof<myclass>.property(e => e.myproperty); }
Comments
Post a Comment