106

In C#, is there a function that returns the current class/method name?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Craig Johnston
  • 7,467
  • 16
  • 40
  • 47

6 Answers6

198

Current class name:

this.GetType().Name;

Current method name:

using System.Reflection;

// ...

MethodBase.GetCurrentMethod().Name;

Since you're using this for logging purposes, you may also be interested in getting the current stack trace.

Cameron
  • 96,106
  • 25
  • 196
  • 225
  • 37
    Current class name for non-static methods: `this.GetType().Name;` Current class name for static methods: `System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;` – James Furey Oct 17 '12 at 00:44
  • 1
    What do to with respect to the "Possible System.NullReferenceException", indicated by the ReSharper for example? – Pedro Dusso Dec 18 '13 at 10:04
  • @Pedro: Hmm, good question. I don't think either of those methods ever return null in practice, though... – Cameron Dec 18 '13 at 12:25
  • 1
    MethodBase.GetCurrentMethod().Name??"Unknown"; should handle the warning while giving the most appropriate result to the situation if in fact it ever actually does occur. – bielawski Feb 20 '20 at 15:14
  • 2
    Using reflection is expensive and is sometimes unnecessary. The question typically stems from an aversion to hard-coding the name - despite actually knowing it. But you can let the compiler handle it by using nameof() in place of the string. True, it doesn't save you from copy/paste errors where the method reference ends up being valid but its speed makes it quite useful none-the-less. – bielawski Feb 20 '20 at 16:07
13

System.Reflection.MethodBase.GetCurrentMethod()

Gabe
  • 84,912
  • 12
  • 139
  • 238
11
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType
abatishchev
  • 98,240
  • 88
  • 296
  • 433
sajoshi
  • 2,733
  • 1
  • 18
  • 22
9

I changed the above example a little into this piece of working example code:

public class MethodLogger : IDisposable
{
    public MethodLogger(MethodBase methodBase)
    {
        m_methodName = methodBase.DeclaringType.Name + "." + methodBase.Name;
        Console.WriteLine("{0} enter", m_methodName);
    }

    public void Dispose()
    {
        Console.WriteLine("{0} leave", m_methodName);
    }
    private string m_methodName;
}

class Program
{
    void FooBar()
    {
        using (new MethodLogger(MethodBase.GetCurrentMethod()))
        {
            // Write your stuff here
        }
    }
}

Output:

Program.FooBar enter
Program.FooBar leave
Jan Wilmans
  • 665
  • 6
  • 10
5

Yes! The MethodBase class's static GetCurrentMethod will inspect the calling code to see if it's a constructor or a normal method, and returns either a MethodInfo or a ConstructorInfo.

This namespace is a part of the reflection API, so you can basically discover everything that the run-time can see by using it.

Here you will find an exhaustive description of the API:

http://msdn.microsoft.com/en-us/library/system.reflection.aspx

If you don't feel like looking through that entire library here is an example I cooked up:

namespace Canvas
{
  class Program
  {
    static void Main(string[] args)
    {
        Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod());
        DiscreteMathOperations viola = new DiscreteMathOperations();
        int resultOfSummation = 0;
        resultOfSummation = viola.ConsecutiveIntegerSummation(1, 100);
        Console.WriteLine(resultOfSummation);
    }
}

public class DiscreteMathOperations
{
    public int ConsecutiveIntegerSummation(int startingNumber, int endingNumber)
    {
        Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod());
        int result = 0;
        result = (startingNumber * (endingNumber + 1)) / 2;
        return result;
    }
}    
}

The output of this code will be:

Void Main<System.String[]> // Call to GetCurrentMethod() from Main.
Int32 ConsecutiveIntegerSummation<Int32, Int32> //Call from summation method.
50 // Result of summation.

Hope I helped you!

JAL

Jose Alava
  • 61
  • 1
  • 1
2

You can get the current class name, but I can't think of anyway to get the current method name. Though, the names of methods for the current can be obtained.

string className = this.GetType().FullName;
System.Reflection.MethodInfo[] methods = this.GetType().GetMethods();
foreach (var method in methods)
    Console.WriteLine(method.Name);
Fun Mun Pieng
  • 6,751
  • 3
  • 28
  • 30