Question

I have a case where I pass a method name to a function as a string, but I don't want it hard-coded. for example

void MyMethodName()
{
    // some code
}

void SomeOtherMethod()
{
    SomeExternalLibrary.ExternalClass.FunctionWithStringParameter("MyMethodName");
}

I want something like this:

FunctionWithStringParameter(MyMethodName.ToString());

THis way I can keep track of method calls by "Find All References", and I can use refactoring without worries.

Was it helpful?

Solution

Perhaps the easiest way would be to provide an overload FunctionWithStringParameter which can take a delegate as a parameter.

The overload could be as simple as:

void FunctionWithStringParameter(Action d)
{
    FunctionWithStringParameter(d.Method.Name);
} 

And call it like this:

FunctionWithStringParameter(MyMethodName);

To accept methods with different signatures, you'd have to either provide many different overloads, or accept Delegate as a parameter, like this:

void FunctionWithStringParameter(Delegate d)
{
    FunctionWithStringParameter(d.Method.Name);
} 

Unfortunately, if you do this, you would have to call it by specifying a delegate type:

FunctionWithStringParameter((Action)MyMethodName);

OTHER TIPS

One technique used a lot these days is to pass an Expression.

FunctionWithStringParameter(x => MyMethodName(x));

Inside your method you can pick the expression apart to get the method name being called (and check that it is a simple method call expression).

See Retrieving Property name from lambda expression for ideas on how to pick apart the lambda expression.

I'm not sure what you are trying to do, but one way to avoid "magic strings" when referencing methods and properties is do do what the ASP.NET MVC Helpers methods do that look like this :

@Html.TextBoxFor(m=> m.SomeProperty)

and do some kind of helper that allows you to do :

string methodName = ReflectionHelper.MethodNameFor<TheTypeWIthTheMethod>(x=> x.TheMethod())

The implementation would look something like that :

static string MethodNameFor<T>(Expression<Action<T>> expression)
 {
        return ((MethodCallExpression)expression.Body).Method.Name;
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top