KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I happy coded quite a project that works fine and do not manifest any oddities at runtime. So I've decided to run static code analysis tool (I'm using Visual Studio 2010). It came out that rule CA2000 is being violated, message as follows: Warning - CA2000 : Microsoft.Reliability : In method 'Bar.getDefaultFoo()', call System.IDisposable.Dispose on object 'new Foo()' before all references to it are out of scope. The code refered goes like this: private static IFoo getDefaultFoo() { return (Baz.canIDoIt()) ? new Foo() : null; } I thought myself: maybe conditional expression spoils the logic (mine or validator's). Changed to this: private static IFoo getDefaultFoo() { IFoo ret = null; if (Baz.canIDoIt()) { retFoo = new Foo(); } return ret; } Same thing happened again, but now the object was referred to as retFoo . I've googled, I've msdn'ed, I've stackoverflow'ed. Found this article . There are no operations I need done after creating the object. I only need to return the reference to it. However, I have tried to apply the pattern suggested in OpenPort2 example. Now code looks like this: private static IFoo getDefaultFoo() { Foo tempFoo = null; Foo retFoo = null; try { if (Baz.canIDoIt()) { tempFoo = new Foo(); } retFoo= tempFoo; tempFoo = null; } finally { if (tempFoo != null) { tempFoo.Dispose(); } } return retFoo; } Same message again, but tempFoo variable is rule violator this time. So basically, code went twisted, longer, little irrational, unnecesarrily complex and does the very same, but slower. I've also found <a href="https://stackoverflow.com/questio
Tags (comma-separated)
Save Edits
Cancel