Link

Throw Expressions

Microsoft Docs / Throw Expressions

Recommendation

Use throw expressions to simplify null checks when possible.

Use:

_execute = execute ?? throw new ArgumentNullException(nameof(execute));

Not:

if (execute == null)
    throw new ArgumentNullException(nameof(execute));

_execute = execute;

Justification

Both the Roslyn and .NET Core runtime teams agree that using this language feature is desirable.

Arguments

✔ Typically reduces 3-5 lines of code down to 1.

❌ Line length does increase with a chance of exceeding 80-120 characters.

❌ Only available in C# 7+

Performance

Method Mean Error StdDev
NoThrowExpression 2.201 ns 0.0307 ns 0.0272 ns
ThrowExpression 2.184 ns 0.0032 ns 0.0027 ns

Note: there are no managed memory allocations, so this stat is omitted.

Benchmark code

Benchmark IL

Exceptions

Analyzers

ID Name Value
IDE0016 csharp_style_throw_expression true:suggestion

Discussion

GitHub Discussion