How to programmatically determine the current method name

If you want to determine the current method in code (C#) here is the line of code you need.

MethodInfo.GetCurrentMethod().Name

This call will return the current method name as a string.  (It is from the namespace System.Reflection).

Why is this helpful?  If you write a generic logging routine and want to log the current method this is a big help.  So you don’t need to modify your log error call (in your catch) with anything not generic (like hard coding your method name).

 

Here is an example of this.

String currentMethodName = MethodInfo.GetCurrentMethod().Name;

 

If this line is in the Page_Load method, it returns “Page_Load”