switch expression csharp

Code Example - switch expression csharp

                
                        var switchValue = 3;
var resultText = switchValue switch
{
    1 or 2 or 3 => "one, two, or three",
    4 => "four",
    5 => "five",
    _ => "unknown",
};
                    
                
 

switch csharp

                        
                                int something = 2;

switch(something)
{
  case 1:
    Console.WriteLine(1);
    break;
  case 2:
    Console.WriteLine(2);
    break;
}
                            
                        
 

csharp switch

                        
                                int caseSwitch = 1;	
switch (caseSwitch)
      {
          case 1:
              Console.WriteLine("Case 1");
              break;
          case 2:
              Console.WriteLine("Case 2");
              break;
          default:
              Console.WriteLine("Default case");
              break;
      }
                            
                        
 

csharp switch case

                        
                                public class Example
{
  // Button click event
  public void Click(object sender, RoutedEventArgs e)
  {
            if (sender is Button handler)
            {
                switch (handler.Tag.ToString())
                {
                  case string tag when tag.StartsWith("Example"):
                       // your code
                    break;
                    
                  default:
                    break;
                }
            }
  }
}
                            
                        
 

csharp return switch

                        
                                return a switch
    {
        1 => "lalala",
        2 => "blalbla",
        3 => "lolollo",
        _ => "default"
    };
                            
                        
 

csharp switch when

                        
                                /*
	Why use many "if" statements if you can just use a switch
	and clean alot of your code!

	Below are two ways to make your life alot easier!
*/

// Using a traditional switch statement

string test = "1";
switch (test)
{
	case "*":
		Console.WriteLine("test");
		break;

	case "Something else":
		Console.WriteLine("test1");
		break;

	case string when test != "*":
		Console.WriteLine("test2");
		break;

  	default:
	Console.WriteLine("default");
		break;
}

// Using a switch expression
// This obviously results in much cleaner code!

string result = test switch
{
	"*" => "test",
	"test" => "test1",
	string when test != "*" => "test2",
	_ => "default" // In switch expressions the _ is the same as default
};

Console.WriteLine(result);