5

I'm going through some old C#.NET code in an ASP.NET application making sure that all SqlConnections are wrapped in using blocks.

I know that using is the same as try / finally where it disposes of the object in the finally no matter what happens in the try. If I have a method that returns a value inside the using, even though execution leaves the method when it returns, does it still call .Dispose() on my object before/during/after it's returning?

public static SqlCommand getSqlCommand(string strSql, string strConnect){
    using (SqlConnection con = new SqlConnection(strConnect))
    {
        con.Open();
        SqlCommand cmd = GetSqlCommand();
        cmd.Connection = con;
        cmd.CommandText = strSql;
        return cmd;
    }
}

Update: The accepted answer is the one I think best answers my question but note that this answer caught the stupidity of this code, that I'm returning a command that uses a disposed connection! :P

2 Answers 2

10

Yes. It will dispose of your object. This will actually cause a problem in your code, since the SqlCommand being returned is dependent on the SqlConnection, which will be Disposed of prior to the control flow returning to your caller.

You can, however, use delegates to work around this. A good pattern to handle this is to rewrite your method like so:

public static SqlCommand ProcessSqlCommand(string strSql, string strConnect, Action<SqlCommand> processingMethod)
{ 
    using (SqlConnection con = new SqlConnection(strConnect)) 
    { 
        con.Open(); 
        SqlCommand cmd = GetSqlCommand(); 
        cmd.Connection = con; 
        cmd.CommandText = strSql; 
        processingMethod(cmd); 
    } 
} 

You can then call this like:

ProcessSqlCommand(sqlStr, connectStr, (cmd) =>
    {
        // Process the cmd results here...
    });
Sign up to request clarification or add additional context in comments.

1 Comment

wow, good catch! thanks. this method isn't used in many places (and is old) so I will probably just remove it and create the commands where I need them
4

Yes it will still call dispose.

Run this very simple console application top verify:

   class Program
    {
        static void Main(string[] args)
        {
            TestMethod();
            Console.ReadLine();
        }

        static string TestMethod()
        {
            using (new Me())
            {
                return "Yes";
            }
        }
    }

    class Me : IDisposable
    {
        #region IDisposable Members

        public void Dispose()
        {
            Console.WriteLine("Disposed");
        }

        #endregion
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.