title: Never use Nulls?
body: <p>We are currently going through the long process of writing some coding standards for C#.</p>
  <p>I've written a method recently with the signature</p>
  <pre class="lang-cs prettyprint-override"><code>string GetUserSessionID(int UserID)
  </code></pre>
  <p><code>GetUserSession()</code> returns null in the case that a session is not found for the user.</p>
  <p>in my calling code... I say...</p>
  <pre class="lang-cs prettyprint-override"><code>string sessionID = GetUserSessionID(1)
  if (null == sessionID &amp;&amp; userIsAllowedToGetSession)
  {
     session = GetNewUserSession(1);
  }
  </code></pre>
  <p>In a recent code review, the reviewer said &quot;you should never return null from a method as it puts more work on the calling method to check for nulls.&quot;</p>
  <p>Immediately I cried shenanigans, as if you return string.Empty you still have to perform some sort of check on the returned value.</p>
  <pre class="lang-cs prettyprint-override"><code>if (string.Empty == sessionID)
  </code></pre>
  <p>However, thinking about this further I would never return null in the case of a <code>Collection</code>/<code>Array</code>/<code>List</code>.
  I would return an empty list.</p>
  <p>The solution to this (I think) would be to refactor this in to 2 methods.</p>
  <pre class="lang-cs prettyprint-override"><code>bool SessionExists(int userID);
  </code></pre>
  <p>and</p>
  <pre class="lang-cs prettyprint-override"><code>string GetUserSessionID(int UserID);
  </code></pre>
  <p>This time, <code>GetUserSessionID()</code> would throw a <code>SessionNotFound</code> exception (as it should not return null)</p>
  <p>now the code would look like...</p>
  <pre class="lang-cs prettyprint-override"><code>if(!SessionExists(1) &amp;&amp; userIsAllowedToGetSession))
  {
     session = GetNewUserSession(1);
  }
  else
  {
     session = GetUserSessionID(1);
  }
  </code></pre>
  <p>This now means that there are no nulls, but to me this seems a bit more complicated. This is also a very simple example and I was wondering how this would impact more complicated methods.</p>
  <p>There is plenty of best-practice advise around about when to throw exceptions and how to handle them, but there seems to be less information regarding the use of null.</p>
  <p>Does anyone else have any solid guidelines (or even better standards) regarding the use of nulls, and what does this mean for nullable types (should we be using them at all?)</p>
  <p>Thanks in advance,</p>
  <p>Chris.</p>
  <hr />
  <p><strong>Thanks everyone! LOTS of very interesting discussion there.</strong></p>
  <p>I've given the answer to egaga as I like thier suggestion of Get vs Find as a coding guideline, but all were interesting answers.</p>