title: Pass Function that is potentially a Null Reference Exception as a parameter
body: <p>I'd like to write a helper method that takes a func and a second parameter T, and attempts to invoke it.  If a Null Reference Exception occurs, return T (second parameter).  If it's successful, return the result of the func passed in.  So instead of:</p>
  
  <pre><code>tableRow[rowNum, fieldNamePos].Value != null ? tableRow[rowNum, fieldNamePos].Value.ToString() : "";
  </code></pre>
  
  <p>I could write</p>
  
  <pre><code>Helper.GetDefaultIfNull(tableRow[rowNum, fieldNamePos].Value.ToString,"")
  </code></pre>
  
  <p>Which I believe is more concise and less code. Here's what I have in the GetDefaultIfNull method:</p>
  
  <pre><code>public T GetDefaultIfNull&lt;T&gt;(Func&lt;T&gt; funcToInvoke, T defaultValue)
  {
      T result;
      try
      {
         result = stringFunc.Invoke();
      }
      catch (NullReferenceException)
      {
         result = defaultValue;
      }
  
      return result;
  }
  </code></pre>
  
  <p>When I run tests, this works correctly when passing in a non null reference, however when passing in a null reference, it throws an error when calling the method so it seems to be invoking the function while passing it into the method?  Here is the test code:</p>
  
  <pre><code>[TestMethod]
      public void NULL_EXCEPTION_return_default()
      {
          StringBuilder sb = null;
  
          //Func&lt;string&gt; stringFunc = ; 
          var defaultValue = "";
          var result = new Helper().GetDefaultIfNull(sb.ToString, defaultValue);
  
          Assert.AreEqual(defaultValue, result);
      }
  </code></pre>
  
  <p>Is there a way to do this?</p>