Dotnet logo

.NET Tools

Essential productivity kit for .NET and game developers

How-To's

C# 7.0 and 7.1 support in ReSharper – Throw expressions

ReSharper support for C# 7 and C# 7.1Let’s continue our blog series about ReSharper support for C# 7.0 and C# 7.1! We’ve already blogged about how ReSharper (and Rider) handle out variables, today we’ll look at throw expressions (spec) that are available in C# 7.0.

Throw expressions allow us to throw exceptions from almost any expression, making our code more concise and readable. ReSharper adds inspections, quick-fixes and context actions around these language features.

In this series:

Throw expressions

ReSharper comes with support for throw expressions. The spec doesn’t really give a nice example, but here’s the gist: C# 7.0 adds support for throwing an exception from expression-bodied members, null-coalescing expressions and conditional expressions. This seem like no big deal, but it’s great syntactic sugar! Consider this check for null values (which throws an ArgumentNullException):

if (value == null)
{
    throw new ArgumentNullException(nameof(value));
}

With throw expressions, we can rewrite this to a much more concise version, where we can combine the assignment, the null-coalescing operator, and throwing the ArgumentNullException:

myValue = value ?? throw new ArgumentNullException(nameof(value));

ReSharper has an inspection that checks for this type of construct, and adds the Join null check with assignment quick-fix to rewrite code for us:

Join null check with assignment

Since we can now throw in many expressions, we’ve introduced the Convert to ‘?:’ operator context action which can convert an if/else statement that either assigns or throws, into a conditional check + throw:

Convert if/else with throw to ?: expression

The .throw postfix template also supports this syntax, and can complete throwing e.g. an ArgumentNullException as part of an expression:

Throw postfix template supports throw expression

Download ReSharper Ultimate or check out Rider that takes advantage of ReSharper’s language support updates. We’d love to hear your thoughts.

image description