Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 651
kiss my armpit Avatar asked Oct 17 '12 05:10

kiss my armpit


1 Answers

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)

like image 152
Marc Gravell Avatar answered Oct 27 '22 14:10

Marc Gravell