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

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.

主站蜘蛛池模板: 简阳市| 香格里拉县| 循化| 景德镇市| 龙口市| 肃南| 伊春市| 博爱县| 宁陕县| 抚州市| 陆河县| 兴义市| 秦安县| 遂平县| 岗巴县| 科技| 永春县| 红河县| 台南县| 石柱| 陵川县| 印江| 丹凤县| 肃北| 甘谷县| 巫山县| 黄冈市| 旌德县| 盐亭县| 龙游县| 镇雄县| 清水河县| 麦盖提县| 思南县| 额尔古纳市| 贡山| 阜阳市| 乌什县| 东兴市| 积石山| 临朐县|