Predefined macros for method names

asp.net, c#, c-preprocessor, webforms

Solution

You could use the StackTrace and StackFrame to get the name of the current method

StackTrace st = new StackTrace(); 
StackFrame sf = st.GetFrame(1);
string method = sf.GetMethod().ToString();

For properties, the returned method name will include the magic `get_` or `set_` prefixes.

However, I don't think you can really refactor this into an inline macro or function like you could in C++. But if you do refactor a utility method to DRY this out, you could probably just pop the StackTrace back one step to log the caller's information?

Problem

In C++ there are predefined macros such as `__FUNCTION__`, which compile to a string literal of the function name the macro is used in. ``` void MyFunc() { printf("I'm in %s!", __FUNCTION__); // I'm in MyFunc! } ``` Is there anything similar for C#? I am looking to do this for asp.net web forms: ``` public string MyProperty { get { return (string)ViewState[__PROPERTY__]; } set { ViewState[__PROPERTY__] = value; } } ``` Obviously this doesn't work (otherwise I wouldn't ask the question), I would like to know if there's something similar in C# that doesn't use reflection or have any negative performance impacts versus using a string literal `"MyProperty"`. This will hopefully cut down on typos on my end, but I can think of a few other instances where this would be useful.

Original source