As part of our Visual Studio 2010 development standards (C # 4.0 primarly), we have included code analysis. As I look through the recently submitted code for a new project, I see a ton
CA2000: Microsoft.Reliability: in the "XYZ" method, the "ABC" object is not located along all the exception paths. Call System.IDisposable. the "ABC" object before all references to it go beyond.
warnings. The problem is that nothing I do removes the warning - and I spent hours cleaning the Internet and trying everything I can.
First, let me be clear that I'm not talking about using a simple block to properly manage a local variable - this is not a problem. In my case, these warnings appear when an object is either returned by a method or assigned to another object inside a method.
Here is sample code that contains four such warnings:
public void MainMethod() { var object1 = CreateFirstObject(); // Warning here var object2 = CreateSecondObject(); // Warning here SomeCollectionProperty.Add(object1); SomeCollectionProperty.Add(object2); } private SomeObject CreateFirstObject() { var theObject = new SomeObject() // Warning here { FirstProperty = "some value", // ... }; return theObject; } private SomeOtherObject CreateSecondObject() { var theObject = new SomeOtherObject() // Warning here { FirstProperty = "a different value", // ... }; return theObject; }
I commented on the lines in which the warnings occur.
I tried to reorganize both creation methods as described in the MSDN article ( here ), but warnings still appear.
UPDATE I should note that both SomeObject and SomeOtherObject implement IDisposable.
In addition, although object initializers can be a component of the problem, keep in mind that initializers are isolated from two private methods and have nothing to do with warnings in MainMethod.
Can someone show me how to properly implement these methods to resolve CA2000 warnings?
Sonofffirate
source share