Suppress "Use 'throw' expression" suggestion
C# 7 has introduced new features: pattern matching, our variables, tuples, and many more. It's also introduced throw expression. This allows using the throw
keyword in an expression. For instance:
_foo = foo ?? throw new ArgumentNullException(nameof(foo));
parts.Length > 0 ? parts[0] : throw new InvalidOperationException();
Adding new syntaxes is great, but I don't like this one to check the arguments of a method are not null. Unfortunately, Visual Studio 2017 suggests to use it everywhere it's possible. For example, it suggests to replace the following code:
public class Sample
{
private Foo _foo;
public Sample(Foo foo)
{
if (foo == null) throw new ArgumentNullException(nameof(foo));
_foo = foo;
}
}
By
public class Sample
{
private Foo _foo;
public Sample(Foo foo)
{
_foo = foo ?? throw new ArgumentNullException(nameof(foo));
}
}
I don't care about this suggestion, I just don't have to change my code. However, it displays an annoying message in the error window:
To remove it, create a file GlobalSuppressions.cs
and add this line of code:
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0016:Use 'throw' expression", Justification = "")]
Now, Visual Studio won't suggest this rewrite 😃
Do you have a question or a suggestion about this post? Contact me!