When recording logs or debugging information, you often want to dynamically retrieve “which method of which class is currently executing” within your program.
By using MethodBase.GetCurrentMethod(), part of the C# Reflection feature, you can obtain current execution context information without relying on hard-coding (writing strings directly).
Implementing Current Method Info Retrieval
This approach uses the MethodBase class in the System.Reflection namespace. You can use GetCurrentMethod() to retrieve current method information and access the method name or the class (type) where it is defined via its return value.
The following sample code demonstrates how to automatically embed the class name and method name into the start log of an order processing class.
Sample Code
using System;
using System.Reflection;
namespace LogSample
{
class Program
{
static void Main()
{
var service = new OrderService();
service.CreateOrder();
service.CancelOrder();
}
}
public class OrderService
{
public void CreateOrder()
{
// Get information about the currently executing method
MethodBase currentMethod = MethodBase.GetCurrentMethod();
// Get class name (via DeclaringType property)
string className = currentMethod.DeclaringType.Name;
// Get method name (Name property)
string methodName = currentMethod.Name;
Console.WriteLine($"[LOG] Start: {className}.{methodName}");
// ... Actual order processing ...
}
public void CancelOrder()
{
// Concise way
var method = MethodBase.GetCurrentMethod();
Console.WriteLine($"[LOG] Start: {method.DeclaringType.Name}.{method.Name}");
// ... Cancel processing ...
}
}
}
Execution Result
[LOG] Start: OrderService.CreateOrder
[LOG] Start: OrderService.CancelOrder
Explanation and Technical Points
1. MethodBase.GetCurrentMethod()
This method returns the metadata of the method corresponding to the stack frame of the currently executing code. It can be used in the same way inside both static methods and instance methods.
2. MethodBase.DeclaringType Property
This retrieves the Type object of the class (or structure) where the method is defined. To get the class name as a string, access the .Name property of the returned type. If you need the fully qualified name including the namespace (e.g., LogSample.OrderService), use .FullName.
3. MethodBase.Name Property
This returns the name of the method itself as a string.
Note: Performance
Retrieving information using Reflection incurs a higher processing cost (overhead) compared to normal code execution.
Avoid using it in high-frequency locations, such as inside loops where millisecond-level speed is required. It is recommended for use in situations with limited frequency, such as logging when an exception occurs.
Note that for C# 5.0 and later, there are compiler features (Caller Information) such as the [CallerMemberName] attribute. If performance is a priority, consider using those instead.
