Let’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:
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
if (value == null)
throw new ArgumentNullException(nameof(value));
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
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:
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 postfix template also supports this syntax, and can complete throwing e.g. an
ArgumentNullException as part of an expression: