Object initializer and Dispose when property can throw exception
<p>I've got the following setup:</p>

<pre><code>public class SomeClass
{
  private DirectoryEntry _root;
  private DirectorySearcher _searcher;

  public SomeClass()
  {
    _root = new DirectoryEntry("ldap://bla");
    _searcher = new DirectorySearcher(_root)
      {
        PageSize = int.MaxValue,
        SizeLimit = int.MaxValue
      }
  }
}
</code></pre>

<p>The reason I use int.MaxValue is because in this case I know I'll exceed the defaults, but the number will never be ridiculously large, so I'm fine about that point.</p>

<p>But if I turn on <em>Code Analysis</em> and <em>Microsoft Basic Correctness Rules</em> it complains:</p>

<blockquote>
  <p>Warning   2 CA2000 : Microsoft.Reliability : In method  'SomeClass.SomeClass()', object '&lt;>g_<em>initLocal0' is not disposed along all exception paths. Call System.IDisposable.Dispose on object '&lt;>g</em>_initLocal0' before all references to it are out of scope.</p>
</blockquote>

<p>It's problem is that PageSize and SizeLimit can throw exceptions, and if that happens the <code>G__initLocal0</code> object doesn't get disposed (even if <code>_searcher</code> does get disposed). The exception they can throw is if you assign them to a negative number, which can't happen here but it still complains.</p>

<p>Next I set the properties outside an object intitializer with regular assignment statements, but then ReSharper complains telling me that I should be using Initializer. I could suppress ReSharper, but I like to figure a way of getting things to work without adding suppressing.</p>

<p>So I figured I had to catch the error and I don't like catch errors in my constructors if possible, so I created a property called Searcher like this:</p>

<pre><code>private DirectorySearcher _searcher;
public DirectorySearcher Searcher
{
  get
  {
    if (_searcher != null) return _searcher;
    var searcher = new DirectorySearcher();
    try
    {
      searcher.PageSize = int.MaxValue;
      searcher.SizeLimit = int.MaxValue;
      _searcher = searcher;
    }
    catch
    {
      searcher.PageSize = 1000;
      searcher.SizeLimit = 1000;
    }
    finally
    {
      searcher.Dispose();
    }
    return _searcher;
  }
}
</code></pre>

<p>Now Code Analysis and everything is happy, but I'm not happy with the solution at all.</p>

<p>Any hints?</p>
