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

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

    This doesn't actually answer your question, but given there will be little difference between the compiled versions, I would urge you to write your code in a way that best describes your intentions. Not only is there a better chance of the compiler doing what you expect, but it will make it easier for others to maintain your code.

    If your intention is to branch your program based on the value of one variable/attribute, then a switch statement best represents that intention.

    If your intention is to branch your program based on different variables/attributes/conditions, then a if/else if chain best represents that intention.

    I will grant that cody is right about people forgetting the break command, but almost as frequently I see people doing complicated if blocks where they get the { } wrong, so lines that should be in the conditional statement are not. It's one of the reasons I always include { } on my if statements even if there's one line in it. Not only is it easier to read, but if I need to add another line in the conditional, I can't forget to add it.

提交回复
热议问题