kiss my armpit
kiss my armpit

Reputation: 3519

How to return a method's fully-qualified name on the fly?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcMusicStore.Controllers
{
    public class StoreController : Controller
    {
        //
        // GET: /Store/

        public string Index()
        {
            return "MvcMusicsStore.Controllers.StoreController.Index";
        }

    }
}

How to return a method's fully-qualified name on the fly?

Upvotes: 17

Views: 5867

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499860

If you're using C# 5 you can do this slightly more simply, but this works too:

var method = MethodBase.GetCurrentMethod();
var type = method.DeclaringType;
var fullName = string.Format("{0}.{1}", type.FullName, method.Name);

That's assuming the method isn't overridden, of course. Unfortunately you can't put this into a utility method of course, as otherwise the current method is the utility method.

You can use StackTrace to get round this, but you need to be careful around inlining - if you create a utility method and then call it from within a method which is itself inlined, you'll get the caller of the method you want :(

Upvotes: 7

Marc Gravell
Marc Gravell

Reputation: 1062550

Without any hard coding? Something like maybe?

public string Index()
{
    return GetType().FullName + GetMemberName();
}

static string GetMemberName([CallerMemberName] string memberName = "")
{
    return memberName;
}

Or perhaps prettier:

public string Index()
{
    return GetMemberName(this);
}

static string GetMemberName(
    object caller, [CallerMemberName] string memberName = "")
{
    return caller.GetType().FullName + "." + memberName;
}

(I used static because I assume in the real code you'd want to put the method in a utility class somewhere)

Upvotes: 15

Related Questions