Is there any significant difference between using if/else and switch-case in C#?

前端 未结 20 831
时光取名叫无心
时光取名叫无心 2020-11-22 07:25

What is the benefit/downside to using a switch statement vs. an if/else in C#. I can\'t imagine there being that big of a difference, other than m

20条回答
  •  一生所求
    2020-11-22 07:29

    Side topic, but I often worry about (and more often see) if/else and switch statement get way too large with too many cases. These often hurt maintainability.

    Common culprits include:

    1. Doing too much inside of multiple if statements
    2. More case statements than humanly possible to analyze
    3. Too many conditions in the if evaluation to know what is being looked for

    To fix:

    1. Extract to Method refactoring.
    2. Use a Dictionary with method pointers instead of a case, or use an IoC for added configurability. Method factories also can be helpful.
    3. Extract the conditions to their own method

提交回复
热议问题