Tuesday, December 16, 2008

Get Method or Property Name as String in .Net

There are a few occasions where it is helpful to have the string name of the executing method or property.

The cleanest way that I've been able to devise is to use the query the current stack frame using System.Diagnostics.StackFrame.

string methodName = new StackFrame().GetMethod().Name;

When called from within a property, the name includes the getter/setter prefix: get_ or set_. Therefore, if you want the actual property name, use the following:

string propertyName = new StackFrame().GetMethod().Name.Split('_')[1];

No comments: