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

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

    Something that I just noticed is that you can combine if/else and switch statements! Very useful when needing to check preconditions.

    if (string.IsNullOrEmpty(line))
    {
        //skip empty lines
    }
    else switch (line.Substring(0,1))
    {
        case "1":
            Console.WriteLine(line);
            break;
        case "9":
            Console.WriteLine(line);
            break;
        default:
            break;
    }
    

提交回复
热议问题