Correct use of using statement in C# RRS feed

  • Question

  • I am looking at some C# code for the .NET 1.1 CLR which does this:

    SqlXmlCommand cmd = BuildSqlXmlCommand(connectionString);


    using (cmd.ExecuteStream())


       _valueHolder.AddAnnotation("SendDurationAdapter", timer.ElapsedTimeToMilliseconds());


    Where BuildSqlXmlCommand instantiates the SqlXmlCommand object.

    According to the .NET 1.1 documentation for the using statement in C# this is normal practise:


    However the .NET 3.5 documentation for the same using statement warns against instantiating the object outside the using block:



    You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block. 


    While the code I am looking at does not access the cmd object again - is it ok to leave the code as is? We have some errors which originate at the Microsoft.Data.SqlXml.SqlXmlCommand.ExecuteStream() statement in the perf environment - would it be better to just create the cmd statement within the using block?

    Thursday, November 6, 2008 5:59 PM


  • I would recommend changin it to:
    using (SqlXmlCommand cmd = BuildSqlXmlCommand(connectionString))  
        _valueHolder.AddAnnotation("SendDurationAdapter", timer.ElapsedTimeToMilliseconds());  

    This avoids the issue they are talking aboutm which ensuring that no one tries to access the cmd object again after the using block is complete.
    Please mark the post if it answers your question.
    • Proposed as answer by VIncent Hubert Thursday, November 6, 2008 7:13 PM
    • Marked as answer by Zhi-Xin Ye Thursday, November 13, 2008 10:39 AM
    Thursday, November 6, 2008 6:14 PM