John Smith
John Smith

Reputation: 8851

How to refactor 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;
}

Trying to get in to a local variable the contents of the current class. I can't use a dictionary because of the way strings work (behaving like value types). Is there any way to refactor this so that it doesn't require this many lines to find the chosen liquid class?

Upvotes: 4

Views: 498

Answers (3)

Austin Salonen
Austin Salonen

Reputation: 50235

You can use the indexer that is part of Settings.Default (tested with .Net 4.0):

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

Upvotes: 8

C.Evenhuis
C.Evenhuis

Reputation: 26446

I assume you're looking into a way of "converting" a string into a class name.

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

Another way is having at some point of initialization a lookup Dictionary (the curse word!) which binds each class to a string.

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 191037

You could convert this to a dictionary easily using some lambda magic.

Dictionary<string, Func<string>> stringsToSettings = new ...
stringsToSettings.Add("LiquidClass1", () => Settings.Default.LiquidClass1);

var liquidClass = stringsToSettings["LiquidClass1"]();

Upvotes: 1

Related Questions