Suppress "Use 'throw' expression" suggestion

 
 
  • Gérald Barré

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:

C#
_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:

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));
    }
}

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:

C#
[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!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub