Search code examples
c#reflectionc#-6.0nameof

Using nameof to get name of current method


Have browsed, searched and hoped but cannot find a straight answer.

Is there anyway in C# 6.0 to get the current method name using nameof withouth specifying the method name?

I am adding my test results to a dictionary like this:

Results.Add(nameof(Process_AddingTwoConsents_ThreeExpectedRowsAreWrittenToStream), result);

I would prefer if I would not have to specify the method name explicitly so I can copy+paste the line, a non-working example:

Results.Add(nameof(this.GetExecutingMethod()), result);

If possible I do not want to use Reflection.

UPDATE

This is not (as suggested) a duplicate of this question. I am asking if is explicitly possible to make use of nameof without(!) reflection to get the current method name.


Solution

  • You can't use nameof to achieve that, but how about this workaround:

    The below uses no direct reflection (just like nameof) and no explicit method name.

    Results.Add(GetCaller(), result);
    
    public static string GetCaller([CallerMemberName] string caller = null)
    {
        return caller;
    }
    

    GetCaller returns the name of any method that calls it.