C# Switch Statement Explained

In C#, the switch statement is used to execute a block of code based on the value of an expression. Its basic syntax is as follows:

switch(expression)
{
    case value1:
        // 当expression的值等于value1时执行的代码
        break;
    case value2:
        // 当expression的值等于value2时执行的代码
        break;
    case value3:
        // 当expression的值等于value3时执行的代码
        break;
    default:
        // 当expression的值不匹配任何case时执行的代码
        break;
}

When using a switch statement, the value of the expression will be compared with the values following each case. If a match is found with one of the cases, the code block following that case will be executed. If no match is found with any case, the code block following the default will be executed (if there is a default).

Within each code block of a case, you can write any C# code. Typically, a break statement is needed at the end of each case’s code block to exit the switch statement; otherwise, the next case’s code block will continue to execute. The default keyword can be used to specify a default case to execute the corresponding code block when no values match any case.

It’s worth noting that the expression can be any integer type (including enums and integral types) or string type.

bannerAds