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”

Advertisements

Got something to add?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s