C# 8.0 Switch Expression

What is a Switch Expression in C#?

In C# 7.0, the Switch statements are more powerful with patterns. In Switch expressions, all the cases are expressions so it's a more 'lightweight' version. In the below code, anyone can analyze what exactly it is doing. 

var operation = 2;  
  
var result = operation switch  
{  
    1 => "Case 1",  
    2 => "Case 2",  
    3 => "Case 3",  
    4 => "Case 4",  
};  
  
Console.WriteLine(result); 

In the above code, anyone can find that there is no 'case', 'break'(or return) statement. In Switch expressions, these keywords are not necessary. The colon(:) is replaced with the arrow(=>). It is nothing but expressions, everything after the arrow is an expression. One more keyword is there, i.e., "default". It's also replaced with the "_"(underscore).

The below code shows all the cases with the default.

var operation = 2;  
  
var result = operation switch  
{  
    1 => "Case 1",  
    2 => "Case 2",  
    3 => "Case 3",  
    4 => "Case 4",  
    _ => "No case availabe"  
};  
  
Console.WriteLine(result); 

It is also used for property assignment or various ways we can use a Switch expression. To see the various ways to use Switch expressions, we are creating the simple console application in Visual Studio 2019 because these features are available in the latest Visual Studio version. 

Currently, Visual Studio 2019 Preview is available that you can download from here.

Following are the steps to create a new console application in Visual Studio 2019 Preview.

  1. Open Visual Studio 2019 Preview. 
  2. Select Create a new project => Select Console App (.Net Core) => Provide project name => Click Create button.
  3. Once the console app is created then next we need to set the latest C# version.
  4. Right, click on your project => Select Properties => Once the property window is open => Click on Build from the left menu.
  5. Scroll down to right side page => Click on Advanced button => Advanced Build Settings popup is opened with default language version.
    C# 8.0 New Feature Swtich Expressions
  6. Click on language version dropdown => select C# 8.0 (beta).

    C# 8.0 New Feature Swtich Expressions

  7. Click on save changes.
  8. Open the Program.cs file, copy and paste the following code,
    using System;    
    using System.Collections.Generic;    
        
    namespace CSharp8.NewFeature.SwitchExpressions    
    {    
        class Program    
        {    
            static void Main(string[] args)    
            {    
                Console.WriteLine("C# 8.0 New Feature Swtich Expressions");    
        
                //example1    
                var (a, b, option) = (10, 5, "+");    
        
                var example1 = option switch    
                {    
                    "+" => a + b,    
                    "-" => a - b,    
                    _ => a * b    
                };    
                Console.WriteLine("Example 1 : " + example1);    
        
                //example2    
                var cal = new Calculation(10, 20, "/");    
                var example2 = cal.Operation switch    
                {    
                    "+" => cal.FirstNumber + cal.SecondNumber,    
                    "-" => cal.FirstNumber - cal.SecondNumber,    
                    _ => cal.FirstNumber * cal.SecondNumber,    
                };    
                Console.WriteLine("Example 2 : " + example2);    
                Console.WriteLine("Property Assignment : " + cal.LogLevel);    
        
                //example3    
                var value = 25;    
        
                int example3 = value switch    
                {    
                    _ when value > 10 => 0,    
                    _ when value <= 10 => 1    
                };    
                Console.WriteLine("Example 3 : " + example3);    
        
                //example4    
                var dic = new Dictionary<string, string>();    
                var (key, defaultValue) = ("Jeetendra", "C# Corner");    
        
                var example4 = dic.TryGetValue(key, out string val) switch    
                {    
                    false => defaultValue,    
                    _ => val    
                };    
                Console.WriteLine("Example 4 : " + example4);    
            }    
        }    
        
        public class Calculation    
        {    
            public Calculation(int a, int b, string operation)    
            {    
                this.FirstNumber = a;    
                this.SecondNumber = b;    
                this.Operation = operation;    
            }    
        
            public int FirstNumber { get; set; }    
        
            public int SecondNumber { get; set; }    
        
            public string Operation { get; set; }    
        
            public int LogLevel { get; } = Environment.GetEnvironmentVariable("LOG_LEVEL") switch    
            {    
                "INFO" => 1,    
                "DEBUG" => 2,    
                _ => 0    
            };    
        }    
        
    }
  9. After copying and pasting the code, save changes and click on Run.
  10. The output of the above code you can see in the below screenshot. 
    C# 8.0 New Feature Swtich Expressions 

You can also download this console application from here

Summary

In this article, we discussed what is Switch Expressions in C# 8.0 and how to use it. If you have any suggestions or queries regarding this article, please contact me.

Stay tuned for other concepts of C# 8.0.

“Learn It, Share it.”


Similar Articles