Code inspection: Join null check with assignment
Category: Language Usage Opportunities
ID: JoinNullCheckWithUsage
EditorConfig: resharper_join_null_check_with_usage_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
This inspection supports throw expressions, a new syntax introduced in C# 7.0. A throw expression allows throwing an exception in the middle of another expression, so throwing can now be combined with other tasks such as null-checking. This means that a common operation of checking an argument for null before assigning its value to a variable can now have a more compact look.
In the example below, JetBrains Rider uses a null-coalescing operator to join assignment, checking for null, and throwing an exception into a single statement.
Suboptimal code
public class MyClass{ private string myVariable; public void SetValue(string newValue) { if (newValue == null) { throw new ArgumentNullException(nameof(newValue)); } myVariable = newValue; }}
After the quick-fix
public class MyClass{ private string myVariable; public void SetValue(string newValue) { myVariable = newValue ?? throw new ArgumentNullException(nameof(newValue)); }}