C# 7 introduced new features: pattern matching, out variables, tuples, and more. Among them is the throw expression, which allows using the throw keyword in an expression. For instance:
C#
_foo = foo ?? throw new ArgumentNullException(nameof(foo));
parts.Length > 0 ? parts[0] : throw new InvalidOperationException();
While this new syntax is useful, it is not always the preferred style for null argument checks. Unfortunately, Visual Studio 2017 suggests using it wherever possible. For example, it suggests replacing the following code:
C#
public class Sample
{
private Foo _foo;
public Sample(Foo foo)
{
if (foo == null) throw new ArgumentNullException(nameof(foo));
_foo = foo;
}
}
By
C#
public class Sample
{
private Foo _foo;
public Sample(Foo foo)
{
_foo = foo ?? throw new ArgumentNullException(nameof(foo));
}
}
You may not want to adopt this style, but the suggestion still shows up as an annoying message in the error window:

To remove it, create a file GlobalSuppressions.cs and add this line of code:
C#
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0016:Use 'throw' expression", Justification = "")]
Now, Visual Studio will no longer suggest this rewrite.
Do you have a question or a suggestion about this post? Contact me!