Any way to know if calling method should Dispose the object returned by called method

255 views Asked by At

Is there any way to mark a method so that code analysis or build with give error message to dispose the object returned by method. for e.g. in the following method.

  private void chart1_Click(object sender, EventArgs e)
    {
        Brush sb = GetBlackBrush();
    }

    Brush GetBlackBrush()
    {
        SolidBrush sb = new SolidBrush(Color.Black);
        return sb;
    }

whenever any method called GetBlackBrush, while building the solution in VS2010, i should get a code analysis warning or build error or build warning to indicate that i need to dispose Brush object. I want i should get some indication in chart1_Click() method to dispose brush object.

This is just a sample code,i know we should be using "Using" but here whats the solution.

There is a CA2213 code analysis warning but that is not getting called for this particular example.

2

There are 2 answers

2
b2zw2a On

CA2000 warning is something you might be after, see documentation:

If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead.

Not sure if you can mark it as error but it should pick it up. You might want to enable also CA2213

0
supercat On

There are no particular conventions for indicating which methods transfer ownership of IDisposable objects and the Framework itself is rather inconsistent in that regard. If a method creates and returns a reference to a new SolidBrush without retaining a copy of that reference, then the recipient of that brush should dispose it. If instead the method had done something like:

WeakReference<Brush> myBrush = new WeakReference<Brush>(); // Field of class hosting method

Brush GetBlackBrush()
{
  Brush ret = myBrush.Target;
  if (ret == null)
  {
    ret = new SolidBrush(Color.Black);
    myBrush.Target = ret;
  }
}

then correctness would dictate that the recipient not call Dispose on the object it received [the use of the weak reference would ensure that there would at any moment in time the above code would only leak be a single extra SolidBrush object; if the caller abandons the instance without disposing it, then generally either the GC won't have noticed that the instance was abandoned (in which case the next caller will receive the same one), or it will have already cleaned it up. In either case, no more than abandoned one brush instance would exist at a time. Further, calling Dispose on a brush instance while myBrush held a reference to it would sabotage the next caller of GetBlackBrush().