code analysis: warning CA2000 when using the "using" C# construct - by froufrou

Status : 

  By Design<br /><br />
		The product team believes this item works according to its intended design.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.

Sign in
to vote
ID 469815 Comments
Status Closed Workarounds
Type Bug Repros 3
Opened 6/24/2009 2:00:32 AM
Access Restriction Public


A method using the C# "using" construct generates code analysis warning CA2000 when the same code rewritten to use try / finally does not.
Sign in to post a comment.
Posted by Javier Campos on 3/17/2012 at 10:27 AM
I have this problem aswell... raised a question about it here:
Posted by Jason Burkey on 9/7/2011 at 1:12 PM
Excuse me, but this explanation is either unclear or not correct. I cannot access the contained zip file so I may have a slightly different scenario, but I believe I am seeing the same issue...My code looks like this:

using(SomeObject foo = new SomeObject())
where "SomeObject" is a disposable class from a third party DLL

As far as I can tell, this should not be generating the warning.
Posted by Microsoft on 8/3/2009 at 6:17 PM

Thanks a lot for reporting this. However, this is by design. CA2000 will fire at both try/finally and using cases.
This is because the method set_IsBodyHtml (IsBodyHtml = htmlMessage) may throw, which caused the method to exit without dispose the disposable object MailMessage. The fix for this is move calling property setter out of object initialization (move IsBodyHtml = htmlMessage to the using body block ).
using (var message = new MailMessage("", "", "", ""))
     message.IsBodyHtml = htmlMessage;
For try/finally. The fix is the same: Move calling property setter from object initialization to after object been created.
Please let us know if you have other questions.

With thanks,
VS Code Analysis Tea,
Posted by Microsoft on 6/25/2009 at 1:00 AM
Thanks for your feedback.

We are routing this issue to the appropriate group within the Visual Studio Product Team for triage and resolution.
These specialized experts will follow-up with your issue.