Thursday 2 July 2020

Throw Expressions

I've not been aware until a few days ago that C# (since version 7) features throw expressions, meaning that we can throw exceptions in an expression, not just in a statement. This is very useful combined with the "?" and "??" operators. I've put up an example:

 

class Salary
{
   public string Payer {get; private set;}

    public int Amount {get; private set;}

    public Salary(string payer, int amount)
     {
        this.Payer = payer ?? throw new ArgumentNullException(nameof(payer));
        this.Amount = amount;
     }

     public void IncreaseByPercentage(int percentage)
     {
         this.Amount = percentage > 5
            ? percentage + (this.Amount * percentage / 100)
            : throw new Exception("Increase percentage is too low"); 
     }
}

This nice feature is missing so far in JavaScript, though I think it's been proposed. For the moment we can use an arrow function to get a similar effect, though the resulting code is quite more verbose.

 

class Salary
{

    constructor (payer, amount)
    {
        //does not compile "throw expressions" are not supported so far
        //this.payer = payer ?? throw new Error("ArgumentNullException: payer");
        
        this.payer = payer || (() => {throw new Error("ArgumentNullException: payer");})();
        this.amount = amount;
    }

     increaseByPercentage(percentage)
     {
         this.amount = percentage > 5
            ? percentage + (this.Amount * percentage / 100)
            : (() => {throw new Error("Increase percentage is too low");})(); 
     }
}

It's interesting to note that theres a new feature proposed for C# 9, Simplified null parameter validation that would allow us to rewrite the constructor above like this:

 

public Salary(string payer!, int amount)
     {
        this.Payer = payer;
        this.Amount = amount;
     }

No comments:

Post a Comment