title: Evil use of Maybe monad and extension methods in C#?
body: <p><strong><em>edit 2015</em></strong> This question and its answers are no longer relevant. It was asked before the advent of C# 6, which has the null propagating opertor (?.), which obviates the hacky-workarounds discussed in this question and subsequent answers. As of 2015, in C# you should now use Form.ActiveForm?.ActiveControl?.Name.</p>
  
  <hr>
  
  <p>I've been thinking about the null propagation problem in .NET, which often leads to ugly, repeated code like this:</p>
  
  <p><strong>Attempt #1 usual code:</strong></p>
  
  <pre><code>string activeControlName = null;
  var activeForm = Form.ActiveForm;
  if (activeForm != null)
  {
      var activeControl = activeForm.ActiveControl;
      if(activeControl != null)
      {
          activeControlname = activeControl.Name;
      }
  }
  </code></pre>
  
  <p>There have been a few discussions on StackOverflow about a Maybe&lt;T&gt; monad, or using some kind of "if not null" extension method:</p>
  
  <p><strong>Attempt #2, extension method:</strong></p>
  
  <pre><code>// Usage:
  var activeControlName = Form.ActiveForm
                            .IfNotNull(form =&gt; form.ActiveControl)
                            .IfNotNull(control =&gt; control.Name);
  
  // Definition:
  public static TReturn IfNotNull&lt;TReturn, T&gt;(T instance, Func&lt;T, TReturn&gt; getter)
      where T : class
  {
      if (instance != null ) return getter(instance);
      return null;
  }
  </code></pre>
  
  <p>I think this is better, however, there's a bit of syntactic messy-ness with the repeated "IfNotNull" and the lambdas. I'm now considering this design:</p>
  
  <p><strong>Attempt #3, Maybe&lt;T&gt; with extension method</strong></p>
  
  <pre><code>// Usage:
  var activeControlName = (from window in Form.ActiveForm.Maybe()
                           from control in window.ActiveControl.Maybe()
                           select control.Name).FirstOrDefault();
  
  // Definition:
  public struct Maybe&lt;T&gt; : IEnumerable&lt;T&gt;
        where T : class
  {
      private readonly T instance;
  
      public Maybe(T instance)
      {
          this.instance = instance;
      }
  
      public T Value
      {
          get { return instance; }
      }
  
      public IEnumerator&lt;T&gt; GetEnumerator()
      {
          return Enumerable.Repeat(instance, instance == null ? 0 : 1).GetEnumerator();
      }
  
      System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
      {
          return this.GetEnumerator();
      }
  }
  
  public static class MaybeExtensions
  {
      public static Maybe&lt;T&gt; Maybe&lt;T&gt;(this T instance)
          where T : class
      {
          return new Maybe&lt;T&gt;(instance);
      }
  }
  </code></pre>
  
  <p><strong>My question is</strong>: is this an evil abuse of extension methods? Is it better than the old usual null checks?</p>