Using throw expressions in C#

What are throw expression, and how and when can they be used?

Home DailyDrop

Daily Knowledge Drop

Throw expressions, introduced in C#7, enabled throw to be used as an expression as well as a statement. This allowed throw to be used in contexts which previously where not supported, specifically:

  • Conditional operator
  • Null-coalescing expression
  • Expression-bodied method

Examples

class Song
{
    public string Name { get; set; }

    public string Artist { get; set; }

    // Null-coalescing expression    
    public Song(string name) => Name = name ?? 
        throw new ArgumentNullException(nameof(name));

    public string GetOutputString()
    {
        // Conditional operator
        return !string.IsNullOrEmpty(Artist) ? 
            $"{Name} by {Artist}" : throw new ArgumentNullException(nameof(Artist));
    }

    // Expression-bodied method
    public void SaveSong() => throw new NotImplementedException();
}
  • Null-coalescing expression: An example of a throw statement being used with a conditional expression.

  • Conditional operator: An example of a throw statement being used in a null-coalescing expression. Generally each operand (the left and right hand side of the : symbol, however in this case a throw expression is allowed.

  • Expression-bodied method: An example of a throw statement being an expression-body for a method. The entire body of the expression is just a throw statement.


Notes

A neat, small, but useful feature to be aware of, and aware of the situations when its possible to use the throw expression.


References

The throw expression
Using throw-expressions in C# 7.0

Daily Drop 62: 28-04-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net throw expressions