Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function to get the name of any method?

Tags:

c#

I would like to have a function called GetMethodName such that the following code would print "myMethod":

int myMethod(string foo, double bar)
{
    // ...
}

Console.Out.WriteLine(GetMethodName(myMethod));

This should work no matter what the method signature myMethod has. Is this possible?

like image 487
JoelFan Avatar asked Dec 09 '22 19:12

JoelFan


2 Answers

No, it's not possible like that. It would be possible with the mythical infoof operator which the C# team would like to include, but haven't got round to yet - but without that, you'd have to use a method group conversion, which will only work if you know the specific type of delegate to use.

The closest you can probably come is to use an expression tree:

public static string GetMethodName(Expression expression)
{
    // Code to take apart the expression tree and find the method invocation
}

GetMethodName(() => myMethod(0, 0));

That wouldn't actually need to call myMethod, but you would need to provide dummy arguments - which could be irritating if there are any out/ref parameters.

like image 74
Jon Skeet Avatar answered Dec 27 '22 06:12

Jon Skeet


As pointed out on Eric Lippert's blog you could fake it with the Action and Func delegates

public static MethodInfo GetInfo<T>(Action<T> action)
{
    return action.Method;
}
public static MethodInfo GetInfo<T, TResult>(Func<T, TResult> func)
{
    return func.Method;
}
public static MethodInfo GetInfo<T, U, TResult>(Func<T, U, TResult> func)
{
    return func.Method;
}   
public static int Target(int v1, int v2)
{
    return v1 ^ v2;
} 
static int Main(string[] args)
{
    var mi = GetInfo<string[], int>(Main);
    Console.WriteLine(mi.Name);

    var mi2 = GetInfo<int, int, int>(Target);
    Console.WriteLine(mi2.Name);
    return 0;
}
like image 23
Matthew Whited Avatar answered Dec 27 '22 06:12

Matthew Whited