Search code examples
c#switch-statementcase-statement

About Cases and switches in c# do we really need them?


I just wrote a program with manny Cases and Switches. So in C# is there any way to avoid Cases and Switches? I ended up with kind of a "messy" program in my point of view. All the other senior full stack developer, they said it was good and so on.

But basically i'm just curious about your thoughts in this subject? Do you know any better way to do smart coding without Cases and Switches?

Basically it's in my nature to questioning things, the status quo....


Solution

  • Each particular case requires its own personal decision. There are cases when hundreds lines of dummy-looked code achieve the goal much better that a beautifully couple- of-lines complex logic with recursions, referneces to 3rd-parties, LINQs and so on.

    But talking about alternatives I can suggest dictionaries:

    var switchCaseAlternative = new Dictionary<string, Action>() 
    {
       {"case1", () => {System.Diagnostic.Debug.WriteLine("One");}},
       {"case2", () => {System.Diagnostic.Debug.WriteLine("Two");}}
    };
    

    then the use instruction will look like:

      switchCaseAlternative["case1"]();