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()?.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());
}
}