Wednesday, December 15, 2021

C# 10.0: Nice Little Features

In this post, let's see a couple of nice features that are available with C# 10.0, which are kind of tends to go unnoticed, but are pretty nice.

Constant Interpolated Strings

With C# 10.0, Interpolated strings can be declared as const. But in order to do that, all the interpolated strings need to be const.

const string Language = "C#";
const string Version = "10.0";
const string FullProductName = $"Language: {Language} Version: {Version}";

For the next features, let's consider the below types.

public enum PackageSize
{
    Small,
    Medium,
    Large
}
 
public record Package(PackageSize PackageSizedecimal Widthdecimal Heightdecimal Length);
 
public record Shipment(string Fromstring ToPackage Package);

Now say, we have a method to Calculate the Package Cost based on the PackageSize. And we are doing a null check on the parameter being passed in.

static decimal CalculatePackageCost(Shipment shipment)
{
    if (shipment == null)
    {
        throw new ArgumentNullException(nameof(shipment));
    }
     
    // TODO: Determine Package Cost
};    

ArgumentNullException.ThrowIfNull

With C# 10.0, Argument Null Check can be simplified as follows.

static decimal CalculatePackageCost(Shipment shipment)
{
    ArgumentNullException.ThrowIfNull(shipment);
             
    // TODO: Determine Package Cost
}   

That's neat!

Now say, we determine the Package Cost by doing something like below. This code is written prior to C# 10.0.

static decimal CalculatePackageCost(Shipment shipment)
{
    // other code
        
    return shipment switch
    {
        { Package: { PackageSize: PackageSize.Small } } => 100.00m,
        { Package: { PackageSize: PackageSize.Medium } } => 150.00m,
        { Package: { PackageSize: PackageSize.Large } } => 200.00m,
        _ => throw new NotImplementedException()
    };
};

Nested Property Patterns

With C# 10.0, you can simplify the code by using Nested Property Pattern.

static decimal CalculatePackageCost(Shipment shipment)
{
    // other code
    
    return shipment switch
    {
        { Package.PackageSize: PackageSize.Small } => 100.00m,
        { Package.PackageSize: PackageSize.Medium } => 150.00m,
        { Package.PackageSize: PackageSize.Large } => 200.00m,
        _ => throw new NotImplementedException()
    };
}

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment