I have a class that look like the following:
public class MyClass
{
...
protected void MyMethod()
{
...
string myName = System.Reflection.M
You'll have issues when running inside async methods. Here's how to fix that:
If you need to fully qualify the class name, you'll have to use DeclaringType.FullName
instead of DeclaringType.Name
This code won't work nicely for anonymous or lambda methods.
using System.Runtime.CompilerServices;
static string GetMethodContextName() {
var name = new StackTrace().GetFrame(1).GetMethod().GetMethodContextName();
return name;
}
static string GetMethodContextName(this MethodBase method) {
if (method.DeclaringType.GetInterfaces().Any(i => i == typeof(IAsyncStateMachine))) {
var generatedType = method.DeclaringType;
var originalType = generatedType.DeclaringType;
var foundMethod = originalType.GetMethods(
BindingFlags.Instance | BindingFlags.Static
| BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.DeclaredOnly)
.Single(m => m.GetCustomAttribute<AsyncStateMachineAttribute>()?.StateMachineType == generatedType);
return foundMethod.DeclaringType.Name + "." + foundMethod.Name;
} else {
return method.DeclaringType.Name + "." + method.Name;
}
}
Here's an example usage:
class Program {
static void Main(string[] args) {
// outputs Program.Main
Console.WriteLine(GetMethodContextName());
}
}
I think these days, it's best to do this:
string fullMethodName = $"{typeof(MyClass).FullName}.{nameof(MyMethod)}";
In C# 6 you can use nameof
:
string myName = nameof(MyMethod);
You can get the full name like this:
var fullMethodName = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName;
Extending Ruben's, you can get the full name like this:
var info = System.Reflection.MethodBase.GetCurrentMethod();
var result = string.Format(
"{0}.{1}.{2}()",
info.ReflectedType.Namespace,
info.ReflectedType.Name,
info.Name);
You can add it to a static method that receives a MethodBase parameter and generates the string.
And to get the full method name with parameters:
var method = System.Reflection.MethodBase.GetCurrentMethod();
var fullName = string.Format("{0}.{1}({2})", method.ReflectedType.FullName, method.Name, string.Join(",", method.GetParameters().Select(o => string.Format("{0} {1}", o.ParameterType, o.Name)).ToArray()));