The reason CA2000 occurs is plain and simple: you have a reference to an IDisposable
that hasn't been disposed in your CreateAndUse()
method.
The fact that your extension method disposes of your object is irrelevant. The code analyzer can't assume that the instance is guaranteed to be disposed by the time the extension method is done. What if you end up doing some other stuff with the object within the extension method outside of its using
block? What if that other stuff causes an exception (rendering the using
block unreachable)? Then all of a sudden you have an undisposed object lying around. And that's what CA2000 is trying to guard you against. If nothing else, the code analyzer is smart enough to anticipate all the other ways your code could possibly fail for you.
You can choose to suppress this warning if you can guarantee that your extension method will do nothing with the IDisposable
outside of the using
block, one of the few times the documentation says it is OK to suppress such a warning. On the other hand, the best way to deal with the CA2000 without suppressing it is to prevent it from ever happening in the first place. And the best way to do that, is to just use using
directly the way it was meant to be used:
public void CreateAndUse()
{
List<Item> instances;
using (var p = new Project())
instances = p.LoadItems();
}
As you can see, the scope of the Project
is narrowed down to just one using
block. Pretty clear-cut. No need for an extra layer of indirection, as jgauffin has said.