Note that there are some explanatory texts on larger screens.

plurals
  1. POC#: Should I bother checking for null in this situation?
    primarykey
    data
    text
    <p>Lets say I have this extention method:</p> <pre><code>public static bool HasFive&lt;T&gt;(this IEnumerable&lt;T&gt; subjects) { if(subjects == null) throw new ArgumentNullException("subjects"); return subjects.Count() == 5; } </code></pre> <p>Do you think this null check and exception throwing is really necessary? I mean, when I use the <code>Count</code> method, an <code>ArgumentNullException</code> will be thrown anyways, right?</p> <p>I can maybe think of one reason why I should, but would just like to hear others view on this. And yes, my reason for asking is partly laziness (want to write as little as possible), but also because I kind of think a bunch of null checking and exception throwing kind of clutters up the methods which often end up being twice as long as they really needed to be. Someone should know better than to send null into a method :p</p> <p>Anyways, what do you guys think?</p> <hr> <p><strong>Note:</strong> <code>Count()</code> is an extension method and <em>will</em> throw an <code>ArgumentNullException</code>, not a <code>NullReferenceException</code>. See <a href="http://msdn.microsoft.com/en-us/library/bb338038.aspx" rel="nofollow noreferrer"><code>Enumerable.Count&lt;TSource&gt; Method (IEnumerable&lt;TSource&gt;)</code></a>. Try it yourself if you don't believe me =)</p> <hr> <p><strong>Note2:</strong> After the answers given here I have been persuaded to start checking more for null values. I am still lazy though, so I have started to use the <code>Enforce</code> class in <a href="http://abdullin.com/shared-libraries/" rel="nofollow noreferrer">Lokad Shared Libraries</a>. Can recommend taking a look at it. Instead of my example I can do this instead:</p> <pre><code>public static bool HasFive&lt;T&gt;(this IEnumerable&lt;T&gt; subjects) { Enforce.Argument(() =&gt; subjects); return subjects.Count() == 5; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload