Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One approach which I have used a lot is the <a href="http://en.wikipedia.org/wiki/Null_Object_pattern" rel="nofollow">null object pattern.</a> For example, if a have a factory class which returns different implementations of an interface based on an argument, and the provided argument is not mapped to any of the implementations, I would return a NullObject, e.g.</p> <pre><code> public interface IFoo{ void Bar(); } public class NullFoo{ public void Bar(){ //null behaviour } } public class FooFactory{ public IFoo CreateFoo(int i){ switch(i){ case 1: return new OneFoo(); break; case 2: return new TwoFoo(); break; default: return new NullFoo(); break; } } } </code></pre> <p>When I want get an <code>IFoo</code> from <code>CreateFoo</code>, I don't have to check whether the returned object is null.</p> <p>Obviously, this is just one of the many approaches. There is no "one size fits all" since null can mean different things.</p> <p>Another way to guard against null arguments is to use <a href="http://msdn.microsoft.com/en-us/magazine/ee236408.aspx#id0070015" rel="nofollow">CodeContract preconditions</a>. e.g.</p> <pre><code> public void Foo(Bar x){ Contract.Requires&lt;ArgumentNullException&gt;( x != null, "x" ); //access x } </code></pre> <p>Using Code Contracts allows you to run static code analysis against your code and catch bugs such as <code>Foo(null)</code>. (<a href="http://msdn.microsoft.com/en-us/magazine/hh335064.aspx" rel="nofollow">more here</a>)</p> <p>One more why to do it would be to use a very simple generic extension method:</p> <pre><code>public static class Ex { public static void EnsureNotNull&lt;T&gt;(this T t, string argName) where T:class { if(t == null) { throw new ArgumentNullException(argName); } } } </code></pre> <p>Then you can check your arguments like this:</p> <pre><code> public void Foo(Bar x, Bar y){ x.EnsureNotNull("x"); y.EnsureNotNull("y"); } </code></pre>
 

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