Using block around a static/singleton resource reference

Posted by byte on Stack Overflow See other posts from Stack Overflow or by byte
Published on 2010-05-21T06:26:36Z Indexed on 2010/05/21 6:30 UTC
Read the original article Hit count: 192

Filed under:
|
|

This is interesting (to me anyway), and I'd like to see if anyone has a good answer and explanation for this behavior.

Say you have a singleton database object (or static database object), and you have it stored in a class Foo.

public class Foo
{
    public static SqlConnection DBConn = new SqlConnection(ConfigurationManager.ConnectionStrings["BAR"].ConnectionString);
}

Then, lets say that you are cognizant of the usefulness of calling and disposing your connection (pretend for this example that its a one-time use for purposes of illustration). So you decide to use a 'using' block to take care of the Dispose() call.

using (SqlConnection conn = Foo.DBConn)
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = conn;
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.CommandText = "SP_YOUR_PROC";

        cmd.ExecuteNonQuery();
    }
    conn.Close();
}

This fails, with an error stating that the "ConnectionString property is not initialized". It's not an issue with pulling the connection string from the app.config/web.config. When you investigate in a debug session you see that Foo.DBConn is not null, but contains empty properties.

Why is this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about using