question

TZacks-2728 avatar image
0 Votes"
TZacks-2728 asked karenpayneoregon edited

C# discard with switch

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

dotnet-csharp
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

In the switch statement, the value used in the case statement compares is passed like a parameter

switch (val) {}

In the switch expression, the value used for the pattern matching, is a prefix

val switch {}

As switch expression returns a value, it can used to set a variable value, use as a parameter, or a return value

1 Vote 1 ·
karenpayneoregon avatar image
1 Vote"
karenpayneoregon answered TZacks-2728 commented

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

Best to read Microsoft docs 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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you so much for sharing the code example. i am familiar with switch statement but now see these examples are switch expression.

i do not understand below code. can elaborate this code or convert this to switch statement for better clarity
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))
};
}

Thanks a lot for your help.


0 Votes 0 ·
karenpayneoregon avatar image
1 Vote"
karenpayneoregon answered karenpayneoregon edited

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))
     };



switch.png (12.1 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.