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