- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to write the new Switch Expression in C# 8.0?
The switch expression provides for switch-like semantics in an expression context
switch is a selection statement that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression.
The switch statement is often used as an alternative to an if-else construct if a single expression is tested against three or more conditions.
Example
New way of Writing the Switch
var message = c switch{ Fruits.Red => "The Fruits is red", Fruits.Green => "The Fruits is green", Fruits.Blue => "The Fruits is blue" };
Example 1
class Program{ public enum Fruits { Red, Green, Blue } public static void Main(){ Fruits c = (Fruits)(new Random()).Next(0, 3); switch (c){ case Fruits.Red: Console.WriteLine("The Fruits is red"); break; case Fruits.Green: Console.WriteLine("The Fruits is green"); break; case Fruits.Blue: Console.WriteLine("The Fruits is blue"); break; default: Console.WriteLine("The Fruits is unknown."); break; } var message = c switch{ Fruits.Red => "The Fruits is red", Fruits.Green => "The Fruits is green", Fruits.Blue => "The Fruits is blue" }; System.Console.WriteLine(message); Console.ReadLine(); } }
Output
The Fruits is green The Fruits is green
Advertisements