Note that there are some explanatory texts on larger screens.

plurals
  1. POFxCop (/VS2010 Code Analysis), possible to flag method result as "callers responsibility now" for IDisposable?
    text
    copied!<p>If I write the following code:</p> <pre><code>public void Execute() { var stream = new MemoryStream(); ... } </code></pre> <p>then code analysis will flag this as:</p> <blockquote> <p>Warning 1 CA2000 : Microsoft.Reliability : In method 'ServiceUser.Execute()', call System.IDisposable.Dispose on object 'stream' before all references to it are out of scope. C:\Dev\VS.NET\DisposeTest\DisposeTest\ServiceUser.cs 14 DisposeTest</p> </blockquote> <p>However, if I create a factory pattern, I still might be required to dispose of the object, but now FxCop/Code Analysis doesn't complain. <strike>Rather, it complains about the factory method, not the code that calls it.</strike> <em>(I think I had an example that did complain about the factory method, but the one I post here doesn't, so I struck that out)</em></p> <p>Is there a way, for instance using attributes, to move the responsibility of the IDisposable object out of the factory method and onto the caller instead?</p> <p>Take this code:</p> <pre><code>public class ServiceUser { public void Execute() { var stream = StreamFactory.GetStream(); Debug.WriteLine(stream.Length); } } public static class StreamFactory { public static Stream GetStream() { return new MemoryStream(); } } </code></pre> <p>In this case, there are no warnings. I'd like FxCOP/CA to still complain about my original method. It is still my responsibility to handle that object.</p> <p>Is there any way I can tell FxCOP/CA about this? For instance, I recently ventured into the annotation attributes that ReSharper has provided, in order to tell its analysis engine information it would otherwise not be able to understand.</p> <p>So I envision something like this:</p> <pre><code>public static class StreamFactory { [return: CallerResponsibility] public static Stream GetStream() { return new MemoryStream(); } } </code></pre> <p>Or is this design way off?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload