As everyone else has said, it is vastly preferable to fail early than to get mysterious problems in production because the function didn't do anything when it was expected to. if the function returns for null arguments, as in your example).
Even if the function doesn't return and just throws a NullReferenceException
, it's eaiser to solve a bug when you know that an argument was null. If a function throws a NullReferenceException
, you have no idea what was null
or whose fault it was.
I'd like to add that ArgumentNullException
takes a parameter for a reason.
It is better to write
if(myArg == null) throw new ArgumentNullException("myArg");
than to throw an ArgumentNullException
without a paramName
.
This way, if you have an exception from a function that takes five parameters, you'll know which of the parameters caused the problem. This is especially important if you cannot attach a debugger. (For example, on a production web server or an end-user machine)
If you're writing many functions, this can be a lot of overhead, especially since there's no IntelliSense for the strings. I wrote a code snippet to generate these checks:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Check for null arguments</Title>
<Shortcut>tna</Shortcut>
<Description>Code snippet for throw new ArgumentNullException</Description>
<Author>SLaks</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>Parameter</ID>
<ToolTip>Paremeter to check for null</ToolTip>
<Default>value</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[if ($Parameter$ == null) throw new ArgumentNullException("$Parameter$");
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>