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

前端 未结 20 1155
时光取名叫无心
时光取名叫无心 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:31

    Actually, a switch statement is more efficient. The compiler will optimize it to a look up table where with if/else statements it cannot. The down side is that a switch statement can't be used with variable values.
    You can't do:

    switch(variable)
    {
       case someVariable
       break;
       default:
       break;
    }
    

    it has to be

    switch(variable)
    {
      case CONSTANT_VALUE;
      break;
      default:
      break;
    }
    

提交回复
热议问题