How to reorganize this switch statement?

string liquidClass = string.Empty; switch (cmbLiquidClass.Text) { case "LiquidClass1": liquidClass = Settings.Default.LiquidClass1; break; case "LiquidClass2": liquidClass = Settings.Default.LiquidClass2; break; case "LiquidClass3": liquidClass = Settings.Default.LiquidClass3; break; case "LiquidClass4": liquidClass = Settings.Default.LiquidClass4; break; case "LiquidClass5": liquidClass = Settings.Default.LiquidClass5; break; case "LiquidClass6": liquidClass = Settings.Default.LiquidClass6; break; case "LiquidClass7": liquidClass = Settings.Default.LiquidClass7; break; case "LiquidClass8": liquidClass = Settings.Default.LiquidClass8; break; case "LiquidClass9": liquidClass = Settings.Default.LiquidClass9; break; } 

An attempt to enter a local variable in the contents of the current class. I cannot use the dictionary because of how strings work (behaving like value types). Is there a way to reorganize this so that it does not require that many lines find the selected fluid class?

+4
source share
3 answers

You can use the index, which is part of Settings.Default (tested with .Net 4.0):

 var liquidClass = Settings.Default[cmbLiquidClass.Text].ToString(); 
+8
source

You can easily convert this to a dictionary with some lambda magic.

 Dictionary<string, Func<string>> stringsToSettings = new ... stringsToSettings.Add("LiquidClass1", () => Settings.Default.LiquidClass1); var liquidClass = stringsToSettings["LiquidClass1"](); 
+1
source

I assume that you are learning how to "convert" a string to a class name.

You can use reflection, which allows you to find a class by name, but it is slow, and if you ever want to rename your class in a future version, your code will not work.

Another way is that at some point in the initialization, there is a search dictionary (curse word!) That links each class to a string.

0
source

All Articles