Using nameof to get name of current method

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.


Building on user3185569's great answer:

public static string GetMethodName(this object type, [CallerMemberName] string caller = null)
{
    return type.GetType().FullName + "." + caller;
}

Results in you being able to call this.GetMethodName() anywhere to return the fully qualified method name.


Same as others, but some variation:

    /// <summary>
    /// Returns the caller method name.
    /// </summary>
    /// <param name="type"></param>
    /// <param name="caller"></param>
    /// <param name="fullName">if true returns the fully qualified name of the type, including its namespace but not its assembly.</param>
    /// <returns></returns>
    public static string GetMethodName(this object type, [CallerMemberName] string caller = null, bool fullName = false)
    {
        if (type == null) throw new ArgumentNullException(nameof(type));
        var name = fullName ? type.GetType().FullName : type.GetType().Name;
        return $"{name}.{caller}()";
    }

Allows to call it like this:

Log.Debug($"Enter {this.GetMethodName()}...");