The C # preprocessor does not support macros with related values, such as C ++, but what you are trying to do can be done using compilers that support C # 5.0 and above (at least VS2012 +) using the compiler generated Caller Information . In particular, through CallerMemberNameAttribute from the System.Runtime.CompilerServices namespace. Based on your interrogation code, I created the following example to illustrate how you can do what you want:
using System; class ViewState { public string this[string propertyName] { get { return propertyName; } set { } } }; class View { ViewState mState = new ViewState(); static string GetCallerName( [System.Runtime.CompilerServices.CallerMemberName] string memberName = "") { return memberName; } public string MyProperty { get { return (string)mState[GetCallerName()]; } set { mState[GetCallerName()] = value; } } }; class Program { static void Main(string[] args) { var view = new View(); Console.WriteLine(view.MyProperty); Console.ReadKey(); } };
"MyProperty" will be printed on the console. At compilation, the compiler will replace the default value for the memberCName GetCallerName argument with the name of the calling construct (property, method, etc.). Therefore, the programmer does not require code maintenance
It should also be noted that this has the added benefit that you can play well with obfuscation tools if they happen after compilation.
source share