How can I use a string as a method name in C#? -


i made short method make easier change console color.

string c = red; if (c == "red")     console.foregroundcolor = consolecolor.red; 

i have every color. can type color method , use string color name? like:

string c = red; console.foregroundcolor = consolecolor.c; 

so don't need specify every color. hope mean.

i think you're looking enum.tryparse method, take string , try convert enum value (in case you're working consolecolor enum). if parsing successful, method returns true , out parameter contain converted value; otherwise returns false.

here's example of method takes string , changes console color if conversion successful:

static bool trychangeconsoleforecolor(string newcolor) {     consolecolor forecolor;      if (enum.tryparse(newcolor, true, out forecolor))     {         console.foregroundcolor = forecolor;         return true;     }      return false; } 

usage

static void main() {     string color = "red";      console.writeline($"changing color '{color}'...");     trychangeconsoleforecolor(color); // ignores return value      color = "car";      console.writeline($"changing color '{color}'...");     if (!trychangeconsoleforecolor(color))     {         // if trychange fails         console.writeline($"cannot change color '{color}'");     }      console.resetcolor();     console.write("\ndone!\npress key exit...");     console.readkey(); } 

output

enter image description here


Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -