If you want to Throw an ArgumentNullException
e.g. to check method parameters, there is a handy one-liner to do this:
_ = x ?? throw new ArgumentNullException(nameof(x));
Here, we try to assign the parameter to the discard _
operator. The ??
-operator performs a nullcheck. If the variable is null, the exception is thrown.
In Visual Studio you can add a custom snippet to bind this line to the shortcut arg0
. You only need to type arg0
, double press the TAB key, and to type the parameter name. Implementing a null check then only takes 2 seconds.
Here is the snippet. To import it into Visual Studio, please use this guide: https://learn.microsoft.com/de-de/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2019
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Argument null check for parameters</Title>
<Shortcut>arg0</Shortcut>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[_= $param$ ?? throw new ArgumentNullException(nameof($param$));]]>
</Code>
<Declarations>
<Literal>
<ID>param</ID>
<ToolTip>Name of the parameter.</ToolTip>
<Default>x</Default>
</Literal>
</Declarations>
</Snippet>
</CodeSnippet>