Raheel Khan
Raheel Khan

Reputation: 14787

Get the name of the current executing function from within the function in C#

Is there a way to programatically get the name of which method or property the current code is executing under?

void Test() { MessageBox.Show("This is a message from " + GetNameOfCurrentMethod); }

I thought about throwing an exception, catching it and parsing the stack trace but there should be a better way to do this.

Upvotes: 2

Views: 1133

Answers (4)

Dave S
Dave S

Reputation: 775

Not currently relevant but for future readers .NET 4.5 introduces a CallerMemberNameAttribute which can be applied to optional method parameters to get the caller information (providing it doesn't get removed from Beta to RTM!). http://msdn.microsoft.com/en-us/library/hh534540(v=vs.110).aspx

Upvotes: 0

Mert Akcakaya
Mert Akcakaya

Reputation: 3129

Have you searched? C# how to get the name of the current method from code

Upvotes: 1

Tudor
Tudor

Reputation: 62439

Try:

MethodInfo.GetCurrentMethod().Name

Upvotes: 4

Vishal Suthar
Vishal Suthar

Reputation: 17193

System.Reflection.MethodBase.GetCurrentMethod().Name;

Upvotes: 2

Related Questions