0

I frequently apply null checks to my parameters when developing in C# (like any good developer should!).

Because I can be lazy, I'd prefer to let Visual Studio add these for me, which it can.

However, when it adds the null checks, it consumes 4 lines of code per check. For example:

if (a is null)
{
    throw new ArgumentNullException(nameof(a));
}

That's ridiculous!

In an ideal world, it would just add a ! to the parameter name, some silly people canceled that feature, so I go for the second best option:

    _ = a ?? throw new ArgumentNullException(nameof(a));

Is there a way I can make Visual Studio 2022 work with me on this?

Brian Kessler
  • 2,187
  • 6
  • 28
  • 58
  • try modifying the settings for code style and formatting.under Tools > Options > Text Editor > c# > Code Style. if you scrolled down there is a 'null' checking section – Nour Apr 27 '23 at 13:33
  • @Nour, do I need to be explicit that I am using Visual Studio 2022 Pro? I can't find any null checking section in formatting. I see General, Indentation, New Lines, Spacing, and Wrapping. Searching for "null" yields "No results found". – Brian Kessler Apr 27 '23 at 13:57
  • I think Nour means this: https://i.stack.imgur.com/cp8Lj.png – Timothy G. Apr 27 '23 at 14:28
  • Unfortunately that setting has no effect! (I just tried it). Most annoying. Somewhat related: https://github.com/dotnet/runtime/issues/68326 – Matthew Watson Apr 27 '23 at 14:30
  • @MatthewWatson, that works (for me), but only when the value will be assigned, not when it will be discarded (which is the context I'm presently concerned with). – Brian Kessler Apr 27 '23 at 14:32
  • @Nour, Thanks for the clarification. I actually already had that configured, but it isn't working when I want to discard instead of assign the value. – Brian Kessler Apr 27 '23 at 14:34

0 Answers0