Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get caller methods name?

Is there a way to get all caller of C# method ie:

public string Caller(string str)
{      
  Customer cust = new Customer();
  cust.Firstname = "Peter";
  cust.LastName = "Beamer";
  string t = getName(cust);
  return t;
}

private string getName(Customer customer)
{
  return customer.Firstname +" "+ customer.LastName;
}

would return: Caller.

All I can get now is method body text using EnvDTE.CodeFunction. Maybe there is a better way to achieve it than trying to parse this code.

Note: I don't want to get current method's calling method name. I want that If I give name of the method then It will return passed method's calling methods name.

like image 811
ChandniShah Avatar asked Jul 07 '26 14:07

ChandniShah


1 Answers

new StackFrame(1, true).GetMethod().Name

Note that in release builds the compiler might inline the method being called, in which case the above code would return the caller of the caller, so to be safe you should decorate your method with:

[MethodImpl(MethodImplOptions.NoInlining)]

source: https://stackoverflow.com/a/1310148/1714342

like image 73
Kamil Budziewski Avatar answered Jul 09 '26 05:07

Kamil Budziewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!