The Oddler The Oddler - 1 year ago 91
C# Question

Get name of function in c#

In Unity when using coroutines or InvokeRepeating, you have to give a string with the name of the function you want to call. Though this is a pain if you change the name of that function, since you have to remember to change the coroutines that use it. Is there a cleaner way of doing this?

Currently it looks like this:

InvokeRepeating ("SendChangedValues", SEND_RATE, SEND_RATE);

though it would be nice to have something like

InvokeRepeating (SendChangedValues.Name(), SEND_RATE, SEND_RATE); //or
InvokeRepeating (functions.GetName(SendChangedValues), SEND_RATE, SEND_RATE);

Is this possible in c#? Or something else that makes sure I get an error/warning when I change the function's name without changing those strings.

Edit 1: The cleanest thing I could think of is making a const string with the function's name, and putting it just before the function itself. So it's harder to forget to change the string, since it's right there above it, and I also only have to change that one const string to change all the coroutines.


Answer Source

ahhh.. if it were next the C# version, you could have used the nameof operator.

for now, Does this help your cause?

private static string GetFunctionName(Action method)
 return method.Method.Name;

called using:

string methodName = GetFunctionName(SendChangedValues);

you might want to explore different delegate types.. Action, Func etc.

the only problem with above is that for every method signature, you might need to define the right signature/overloads to get name.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download