Search code examples
c#system.reflectionmethodbase

Getting the MethodBase.GetCurrentMethod() but without Parameters


I have a function

public void AddPerson(string name)
{
    Trace.WriteLine(MethodBase.GetCurrentMethod());
}

The expected output is

void AddPerson(string name)

But I wanted that the methodname outputted has no parameters in it.

void AddPerson()

Solution

  • To do this reliably is going to be an issue, you are going to have to build it up i.e. return type, name, generic types, access modifiers etc.

    E.g:

    static void Main(string[] args)
    {
       var methodBase =  MethodBase.GetCurrentMethod() as MethodInfo;
         
       Console.WriteLine($"{methodBase.ReturnType.Name} {methodBase.Name}()");
    }
    

    Output:

    Void Main()
    

    Pitfalls, you are chasing a moving target:

    public static (string, string) Blah(int index)
    {
       var methodBase =  MethodBase.GetCurrentMethod() as MethodInfo;
       Console.WriteLine(MethodBase.GetCurrentMethod());
       Console.WriteLine($"{methodBase.ReturnType.Name} {methodBase.Name}()");
       return ("sdf","dfg");
    }
    

    Output:

    System.ValueTuple`2[System.String,System.String] Blah(Int32)
    ValueTuple`2 Blah()
    

    The other option is just regex out the parameters with something like this: (?<=\().*(?<!\)).