Partilhar via


Beware of the using statement

The using statement is very handy in keeping your code clean and letting you concentrate on your business logic. Be careful however, especially when employing it while trying to get rid of CA2000 warnings (Dispose objects before losing scope). Never use a using statement on a variable that is to be returned from the function it is declared in. There is no compiler error or warning on this. Even Resharper fails to recognize the problem. Returning the variable declared in the using statement will cause it to dispose before it is returned to the calling function.

[Edit: Added the code samples below for clarity]