I am calling a method from a property. I have to pass property name as attribute of that method. My Property is
string lcl_name = string.Empty;
public string Name
{
get { return lcl_name; }
set
{
if (lcl_name != value)
{
lcl_name = value;
Foo_Method(GetCorrectPropertyName(MethodBase.GetCurrentMethod().Name));
}
}
}
and the method is
public string GetCorrectPropertyName(string propertyName)
{
return propertyName.StartsWith("set_") || propertyName.StartsWith("get_") ?
propertyName.Substring(4) : string.Empty;
}
My seniors say that i should not call Reflection and pass direct string to method this way
Foo_Method("Name");
but in that case since it would be hardcoded and if property name is changed, then method call have to be changed accordingly.
So my question is which one of them would be better in terms of efficiency? Is there something else that my seniors are seeing to which I am oblivious to?
Maybe Expression Trees can help you here.
Instead of
Foo_Methodtaking the property name as stringuse a parameter of type
Expressionto retrieve the property name via a MemberExpression:and call it like this
This way, when renaming
Name, you don’t break your code, sinceFoo_Method(x => x.Name)gets renamed too (when using your IDEs refactoring capabilities for renaming, of course).Edit:
To answer your comment:
If you really can’t add an overload to Foo_Method, you can of course just create another method:
Edit2:
To answer your other comment:
You could create an extension method
but you don’t have to, since the expressions work fine without any instance.
the trick is to use generics here.
The first method would look like this in VB.Net