title: Classes with disposable fields should be disposable
body: <p>The FxCop warning "Classes with disposable fields should be disposable" sometimes confuses me. See contrived example below</p>
  
  <p>Only one type <em>creates</em> and <em>owns</em> the disposable resource, but any number of types can <em>use</em> (or "borrow") this resource. I have seen developes take the FxCop warning on Util1 and Util2 to indicate that since they have a field of a disposable type, they must implement Dispose and dispose that field. That's clearly not what you want here. </p>
  
  <p>Is the problem that</p>
  
  <ol>
  <li><p>Making classes that only borrow disposable resources is an antipattern. The disposable resource could be passed as a method argument to Util1 and Util2, and the problem would go away. Only classes that <em>create</em> disposable resource should ever have them as fields, so that the field itself is what indicates ownership.</p></li>
  <li><p>The warning isn't clever enough. It should be warning when types that <em>own</em>  disposable resources aren't themselves disposable, and in this scenario only one class owns it, while the others borrow it. The fact that it is injected only from a constructor parameter could have been used by a more clever rule to detect that the warning should not be raised for the borrowing class.</p></li>
  <li><p>Something else? </p></li>
  </ol>
  
  <pre class="lang-cs prettyprint-override"><code>static class Program
  {
     public static void Main() 
     {
        using(var r = new SomeResource()) 
        {
            Console.WriteLine(new Util1(r).Foo());   
            Console.WriteLine(new Util2(r).Foo());   
        }                                 
     }
  }
  
  public sealed class SomeResource : IDisposable 
  {
     private readonly NativeResource native;
     public void SomeResource() 
     {
        native = Native.CreateDisposableThing();
     }
     public void Dispose()
     {
        native.Dispose();
     }
  }
  
  public sealed class Util1 {
     private readonly SomeResource res;
     public Util1(SomeResource res) {  this.res = res; }
     public string Foo() { /* uses res */ }
  }
  
  public sealed class Util2 {
     private readonly SomeResource res;
     public Util2(SomeResource res) {  this.res = res; }
     public string Foo() { /* uses res */ }
  }
  </code></pre>