1

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()
JP Dolocanog
  • 451
  • 3
  • 19

2 Answers2

3

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: (?<=\().*(?<!\)).

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
1

The GetCurrentMethod method returns a MethodBase object, not a string. Therefore, if you want a different string than what .ToString() for that returns, you can cobble together a string from the MethodBase properties or just return the Name property, like:

Trace.WriteLine(MethodBase.GetCurrentMethod().Name);
Jacob
  • 77,566
  • 24
  • 149
  • 228
  • But MethodBase.GetCurrentMethod().Name returns only "AddPerson". – JP Dolocanog Oct 25 '18 at 00:52
  • Like I said, you can cobble together a string from the `MethodBase` properties. I sent a link to the docs so you can see which properties you want to include in your string. Your question wasn't specific on what you did and did not want included from the base `.ToString()` method, like how you wanted to handle generics. Sad that I get downvoted for not reading minds. – Jacob Oct 25 '18 at 01:03