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 to use 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 clearly 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 😃

Comments

Artur Karbone -

Nice trick, @meziantou. Was not aware of that attribute. I used #pragma warning disable IDE0016 for this. Am I right that I can call the file whatever I want, not only GlobalSuppressions.cs?

Meziantou -

Yes, you can use the name you want for the file. GlobalSuppression.cs is the name generated by Visual Studio when you use the light bulb action.

neoKushan -

Good tip and very useful to know. Out of curiosity (and not looking to start an argument), what's your reasoning for not liking the new syntax? Is it just preference, or do you think the old way is cleaner/neater/easier to read?

Meziantou -

It's just a preference, and it depends of the context. For instance, in a constructor that only assigns fields or properties, the new syntax is ok. However, I don't want to use this syntax to throw ArgumentNullException in the middle of a method. Plus, I don't want a message (hundreds sometimes) in the error box because I don't want to use the new syntax in this case!

Leave a reply