Moving to .NET Core 5, C#9 provides many benefits
found here for .NET Core 5 over former versions of .NET Core and new features for C# 9 found here.
Also, .NET Core 3 has reached end of life
.
Some new features
Ranges
var list = new List<string> {"abc", "def", "ghi"};
Range range = new Range(0, ^1);
List<string> subList1 = list.GetRange(range);
List<string> subList = list.GetRange(0..1);
Console.WriteLine($"{string.Join(",", subList1.ToArray())}");
Console.WriteLine($"{string.Join(",", subList.ToArray())}");
Switches
/// <summary>
/// Any version of C#
/// </summary>
/// <param name="caseSwitch"></param>
private static void Conventional1(int caseSwitch)
{
switch (caseSwitch)
{
case 1:
Operations.Case1();
break;
case 2:
Operations.Case2();
break;
default:
throw new ArgumentOutOfRangeException("Dude, unknown int for case");
}
}
/// <summary>
/// C# 8, 9
/// </summary>
/// <param name="caseSwitch">int</param>
private static void ExpressionBodiedMember1_int(int caseSwitch) =>
(
caseSwitch switch
{
1 => (Action)Operations.Case1,
2 => Operations.Case2,
_ => throw new ArgumentOutOfRangeException("Dude, unknown int for case")
})
();
/// <summary>
/// C# 8, 9
/// </summary>
/// <param name="caseSwitch">ApplicationRoles</param>
private static void ExpressionBodiedMember1_enum(ApplicationRoles caseSwitch) =>
(
caseSwitch switch
{
ApplicationRoles.User => (Action)Operations.Case1,
ApplicationRoles.Admin => Operations.Case2,
_ => throw new ArgumentOutOfRangeException("Dude, unknown member for case")
})
();
Testing for null
private void Nulls(Countries countries)
{
if (countries == null)
{
// any version of C#
}
if (countries is null)
{
// C#9
}
if (countries is {})
{
// C#9
}
}