ChandniShah
ChandniShah

Reputation: 249

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.

Upvotes: 2

Views: 1438

Answers (3)

Roy Dictus
Roy Dictus

Reputation: 33139

While it is certainly possible to do it using StackFrame as wudzik points out, why would you need to do this?

This is a design smell. If your code has to have knowledge about its caller, something is wrong with your design. Every such dependency should be abstracted out of your class model.

Upvotes: 4

Tim
Tim

Reputation: 15227

Not really positive I understand what you're asking since no one seems sure what should return "Caller"... but, perhaps the CallerMemberNameAttribute might be of some help?

Upvotes: 5

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

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

Upvotes: 6

Related Questions