C# discard with switch

T.Zacks 3,986 Reputation points
2022-05-15T07:32:15.497+00:00

Normally we write switch statement in c# like this way

int day = 4;
switch (day) 
{
  case 1:
    Console.WriteLine("Monday");
    break;
  case 2:
    Console.WriteLine("Tuesday");
    break;
  case 3:
    Console.WriteLine("Wednesday");
    break;
  case 4:
    Console.WriteLine("Thursday");
    break;
  case 5:
    Console.WriteLine("Friday");
    break;
  case 6:
    Console.WriteLine("Saturday");
    break;
  case 7:
    Console.WriteLine("Sunday");
    break;
}

i found a new syntax of writing switch but syntax is not clear
what is val here ?

var moreThan20 = val switch
{
    >20 => "Yes",

    >50 => "Yes - way more!",

    _ => "No",
};

i heard in c# now we can return switch too....please some one how can i return switch from one function to another ?

thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,201 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,031 Reputation points
    2022-05-15T08:03:34.327+00:00

    What you are looking at is a switch expression and when starting out a decent example usually clears things up.

    Best to read Microsoft Learn on switch expressions along with pattern matching.

    Edit

    Check out the following .NET Fiddle code sample which is done with a language extension and adds in a when clause.

    See my Microsoft article for more examples.

    Try this out. its easy enough to follow.

    using System;  
      
    namespace SwitchExpressions.Classes  
    {  
        class Howdy  
        {  
            public static string TimeOfDay() => DateTime.Now.Hour switch  
            {  
                <= 12 => "Good Morning",  
                <= 16 => "Good Afternoon",  
                <= 20 => "Good Evening",  
                _ => "Good Night"  
            };  
        }  
    }  
    

    Example 2, conventional and expression which may even be better than the first

    public static double GetRating(this Person sender) =>  
        sender switch  
        {  
            Employee => 2,  
            Manager  => 3,  
            { }      => 1, // null check  
            null     => throw new ArgumentNullException(nameof(sender))  
        };  
      
    public static double GetRatingConventional(this Person sender)  
    {  
        switch (sender)  
        {  
            case Employee:  
                return 2;  
            case Manager:  
                return 3;  
            case { }:  
                return 1;  
            case null:  
                throw new ArgumentNullException(nameof(sender));  
        }  
    }  
      
    

    Example 3, not for first timers

    public static double GetRatingGuarded(this Person sender)  
    {  
        return sender switch  
        {  
            Employee => 2,  
            Manager { Years: >= 4 } manager when manager.Employees.Count > 1 => 7,  
            Manager => 4,  
            Developer { Experience: Experience.Guru } => 10,  
            Developer { Experience: Experience.Novice } => 1,  
            Developer { Experience: Experience.Professional } => 8,  
            { } => 0,  
            null => throw new ArgumentNullException(nameof(sender))  
        };  
    }  
    

    Example 4, highly difficult to read

    public static string FormatElapsed(this TimeSpan span) => span.Days switch  
    {  
        > 0 => $"{span.Days} days, {span.Hours} hours, {span.Minutes} minutes, {span.Seconds} seconds",  
        _ => span.Hours switch  
        {  
            > 0 => $"{span.Hours} hours, {span.Minutes} minutes, {span.Seconds} seconds",  
            _ => span.Minutes switch  
            {  
                > 0 => $"{span.Minutes} minutes, {span.Seconds} seconds",  
                _ => span.Seconds switch  
                {  
                    > 0 => $"{span.Seconds} seconds",  
                    _ => ""  
                }  
            }  
        }  
    };  
    

    I added the last two which should be used only if you can write it yourself.

    Back to easy for the most part to learn from

    public static string ToYesNo(this int sender) => sender switch  
    {  
     0 => "No",  
     1 => "Yes",  
     _ => throw new InvalidOperationException($"Integer value {sender} is not valid")  
    };  
      
    public static string Determination0(this int sender)  
    {  
     var result = "";  
      
     switch (sender)  
     {  
     case < 0:  
     result = "Less than or equal to 0";  
     break;  
     case > 0 and <= 10:  
     result = "More than 0 but less than or equal to 10";  
     break;  
     default:  
     result = "More than 10";  
     break;  
     }  
      
     return result;  
    }  
    /// <summary>  
    /// use Switch expression to determine where a int value falls  
    /// </summary>  
    /// <param name="sender"></param>  
    /// <returns></returns>  
    public static string Determination1(this int sender) => sender switch  
    {  
     <= 0 => "Less than or equal to 0",  
     > 0 and <= 10 => "More than 0 but less than or equal to 10",  
     _ => "More than 10"  
    };  
      
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,031 Reputation points
    2022-05-17T17:58:14.21+00:00

    i do not understand below code. can elaborate this code or convert this to switch statement for better clarity

    Base class

    public class Person  
    {  
        public string FirstName { get; set; }  
        public string LastName { get; set; }  
        public DateTime BirthDate { get; set; }  
    }  
    

    Developer

    public class Developer  : Person  
    {  
        public Experience Experience { get; set; }  
    }  
    

    Employee

    public class Employee : Person  
    {  
        public int EmployeeId { get; set; }  
        public int ManagerId { get; set; }  
    }  
    

    Manager

    public class Manager : Person  
    {  
        public int ManagerId { get; set; }  
        public int Years { get; set; }  
        public List<Employee> Employees = new();  
    }  
    

    Enum

    public enum Experience  
    {  
        Novice,  
        Professional,  
        Guru  
    }  
    

    Mocked people

    List<Person> peopleList = new()  
    {  
        new Employee()  { FirstName = "Mike" },  
        new Developer() { FirstName = "Anne", Experience = Experience.Professional},  
        new Manager()   { FirstName = "Mary", Years = 1, Employees = new List<Employee>()},  
        new Manager()   { FirstName = "Jake", Years = 5, Employees = new List<Employee>() { new(), new() } },  
        new Manager()   { FirstName = "Tina" , Years = 5, Employees = new List<Employee>() { new (), new() } },  
        new Developer() { FirstName = "Karen", Experience = Experience.Guru},  
        new Person()    { FirstName = "Sam" }  
    };  
    

    Method

    public static double GetRatingGuarded(this Person sender)  
    {  
        return sender switch  
        {  
            Employee => 2,  
            Manager { Years: >= 4 } manager when manager.Employees.Count > 1 => 7,  
            Manager => 4,  
            Developer { Experience: Experience.Guru } => 10,  
            Developer { Experience: Experience.Novice } => 1,  
            Developer { Experience: Experience.Professional } => 8,  
            { } => 0,  
            null => throw new ArgumentNullException(nameof(sender))  
        };  
    }  
    

    Example

    foreach (var person in peopleList)  
    {  
        Console.WriteLine($"{person.FirstName,-8}{person.GetRating()}");  
    }  
      
    Console.WriteLine();  
      
    foreach (var person in peopleList)  
    {  
        Console.WriteLine($"{person.FirstName,-8}{person.GetRatingGuarded(),-5}{person.GetType().Name}");  
    }  
    

    202838-switch.png

    public static double GetRating(this Person sender) =>  
        sender switch  
        {  
            Employee => 2,  
            Manager  => 3,  
            { }      => 1,   
            null     => throw new ArgumentNullException(nameof(sender))  
        };  
    
    1 person found this answer helpful.
    0 comments No comments