Samantha J T Star
Samantha J T Star

Reputation: 32758

Can I use an ENUM instead of a switch statement with Enums in the CASE?

I have ENUMs and extensions in my application that I use like this:

   

public enum CO
{
    Random = 0,
    FirstToLast = 1,
    LastToFirst = 2,
}

public static partial class Extensions
{
    public static string Text(this CO cardOrder)
    {
        switch (cardOrder)
        {
            case CO.Random: return "Random";
            case CO.FirstToLast: return "1, 2, 3";
            case CO.LastToFirst: return "3, 2, 1";
        }
        return "";
    }
}

In the codes I have switch statement set to decide to update a database:

    

switch (segControlCardOrder.SelectedValue)
{
   case "Random":
         App.DB.UpdateIntSetting(SET.Co, (int)CO.Random);
         break;
   case "1, 2, 3":
         App.DB.UpdateIntSetting(SET.Co, (int)CO.FirstToLast);
         break;
   case "3, 2, 1":
         App.DB.UpdateIntSetting(SET.Co, (int)CO.LastToFirst);
         break;
}

Is there a way that I could avoid using the switch statement and just call the UpdateIntSettings based on the value of the ENUM?

Upvotes: 1

Views: 115

Answers (3)

Chayim Friedman
Chayim Friedman

Reputation: 70900

Yes, but it is less efficient. You can use a dictionary of the values, like:

var dict = new Dictionary<string, CO> { ["Random"] = CO.Random, ["1, 2, 3"] = CO.FirstToLast, ["3, 2, 1"] = CO.LastToFirst };
App.DB.UpdateIntSetting(SET.Co, (int)dict[segControlCardOrder.SelectedValue]);

Or simply set the value to using in a variable, and pass it to the method. I prefer the last way.

Upvotes: 1

PinBack
PinBack

Reputation: 2554

You can also add an extension method for the other way (from string to enum). Then you can use the method in you statement:

public static CO CardOrder(this string cardOrder)
{
    switch (cardOrder)
    {
        case "Radom": return CO.Random;
        case "1, 2, 3": return CO.FirstToLast;
        case "3, 2, 1":  return CO.LastToFirst;
    }
    throw new ArgumentException(string.Format($"{cardOrder} is not a CO representation"));
}

Simple use:

App.DB.UpdateIntSetting(SET.Co, (int)segControlCardOrder.SelectedValue.CardOrder());

Upvotes: 3

mnieto
mnieto

Reputation: 3874

You can initialise a Dictionary<string, CO> like as private or static member of the class:

dict.Add("Random", CO.Random);
dict.Add("1, 2, 3", CO.FirstToLast);
dict.Add("3, 2, 1", CO.LastToFirst);

And finally do:

App.DB.UpdateIntSetting(Set.CO, (int)dict[segControlCardOrder.SelectedValue]);

Upvotes: 1

Related Questions