Search code examples
c#fxcopmicrosoft.codeanalysisca1001

Correct usage of Using for disposable types


I have this code

using(MyStopWatch st= new MyStopWatch())
{
St.start();
St.stop();
}

Which gives me CA1001 error when I run fxcop And

MyStopWatch st= null;
using( st= new MyStopWatch())
{
St.start();
St.stop();
}

Which does not give any fxcop rule error on analysis, what is the difference between these two cases, whether the second usage creates a memory leak? Is using block not behaving in the way I expect?


Solution

  • Looks like a false positive to me. As far as disposing goes, there should be no difference between your two code samples.

    The first sample is recommended, though, since you likely don't want to be using the disposed object outside of the using scope.