官术网_书友最值得收藏!

Switch statement

This is a statement that provides a way to select an expression using switch statement that evaluates the conditions using case blocks when code does not fall in any of the case blocks; then, the default block executes (default block is an optional block in switch...case statement).

Switch statement is also known as an alternative to if...else if...else statement. Let's rewrite our examples used in the previous section to showcase the if...else if...else statement:

private static void SwitchCaseExample() 
{ 
WriteLine("switch case statement example."); 
Write("Enter character:"); 
charinputChar = Convert.ToChar(ReadLine()); 
 
switch (char.ToLower(inputChar)) 
{ 
case'a': 
WriteLine($"Character {inputChar} is a vowel."); 
break; 
case'e': 
WriteLine($"Character {inputChar} is a vowel."); 
break; 
case'i': 
WriteLine($"Character {inputChar} is a vowel."); 
break; 
case'o': 
WriteLine($"Character {inputChar} is a vowel."); 
break; 
case'u': 
WriteLine($"Character {inputChar} is a vowel."); 
break; 
default: 
WriteLine($"Character '{inputChar}' is a consonant."); 
break; 
} 
}

In the preceding code, the default block will execute if none of the case evaluates to true. The switch...case statement will be discussed in detail on day three.

There is a slight difference when you're choosing between switch...case and if...else. Refer to https://stackoverflow.com/questions/94305/what-is-quicker-switch-on-string-or-elseif-on-type for more details.

主站蜘蛛池模板: 泗阳县| 瓮安县| 理塘县| 汶上县| 榆林市| 南溪县| 沂水县| 辽阳县| 台中市| 贡觉县| 成安县| 都江堰市| 杭州市| 资兴市| 安新县| 通江县| 白城市| 大新县| 明水县| 达州市| 富锦市| 河北省| 九龙坡区| 曲沃县| 永州市| 河津市| 鱼台县| 灵寿县| 平陆县| 石家庄市| 铁力市| 金乡县| 南靖县| 钟山县| 隆回县| 修文县| 吉首市| 福鼎市| 原平市| 阿合奇县| 海口市|