Search code examples
c#coding-styleenums

Better way to handle switch case in C#


I do apologize in advance if my question looks really dumb, but for some reason I can't look through more graceful solution to the problem. So I have a method that utilizes switch - case blocks similar to the below chunk of code:

public enum Items
{
    item_1, item_2, item_3, .... item_N
};

private string String_1 {get; set;}
private string String_2 {get; set;}
private string String_3 {get; set;}
// ...
private string String_N {get; set;}

public void DoSomething(Items item){
    switch(item){
        case item_1:
            MethodNumberOne();
            MethodNumberTwo();
            MethodNumberThree();
            Console.WriteLine($"{0} is displayed on the page", String_1);
            break;

        case item_2:
            MethodNumberOne();
            MethodNumberTwo();
            MethodNumberThree();
            Console.WriteLine($"{0} is displayed on the page", String_2);
            break;

        case item_3:
            MethodNumberOne();
            MethodNumberTwo();
            MethodNumberThree();
            Console.WriteLine($"{0} is displayed on the page", String_3);
            break;
        // ...
        case item_N:
            MethodNumberOne();
            MethodNumberTwo();
            MethodNumberThree();
            Console.WriteLine($"{0} is displayed on the page", String_N);

As it can be seen from the above example switch statement is calling the same methods, and the only difference is the last Console call.

My question: is there a more elegant way to handle this situation as I don't really like the duplication of the code. So far I tried to carry out Items enum to separate class and pass this as parameter, but this approach doesn't work as static class can't be passed as parameter in C#

public static class Items {
    public string String_1 {get; set;}
    public string String_2 {get; set;}
    public string String_3 {get; set;}
    // ...
    private string String_N {get; set;}
}

// ....

public void DoSomething(Items item)
  • not allowing to declare this method

Any suggestions are greatly appreciated..


Solution

  • You could store the enum Items to String_X mapping in a dictionary rather than relying on a switch.

    private IDictionary<Items, string> _itemStringMap = new Dicitionary<Items, string>()
    {
       { Items.item_1, String_1 },
       //Other items here
    };
    
    public void DoSomething(Items item)
    {
      var s = _itemStringMap[item];
    
      MethodNumberOne();
      MethodNumberTwo();
      MethodNumberThree();
      Console.WriteLine($"{0} is displayed on the page", s);
    }
    

    You may want to check that the item argument has a valid mapping and if not use a default string.