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

  • Learn C# in 7 days
  • Gaurav Aroraa
  • 183字
  • 2021-07-08 09:51:29

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.

主站蜘蛛池模板: 博客| 隆林| 手游| 海兴县| 阿图什市| 锦屏县| 友谊县| 万州区| 南开区| 沂源县| 葵青区| 灌云县| 布拖县| 平乡县| 海淀区| 乌拉特前旗| 前郭尔| 无极县| 乌海市| 永吉县| 通化县| 读书| 石阡县| 新兴县| 灌阳县| 清流县| 鹿泉市| 永德县| 奉新县| 凯里市| 淮滨县| 花莲市| 蓬安县| 怀远县| 杂多县| 蓝山县| 沈阳市| 乐亭县| 柳州市| 景谷| 惠安县|