Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a C# using statement perform try/finally?

Suppose that I have the following code:

private void UpdateDB(QuoteDataSet dataSet, Strint tableName)
{
    using(SQLiteConnection conn = new SQLiteConnection(_connectionString))
    {
        conn.Open();
        using (SQLiteTransaction transaction = conn.BeginTransaction())
        {
            using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM " + tableName, conn))
            {
                using (SQLiteDataAdapter sqliteAdapter = new SQLiteDataAdapter())
                {
                    sqliteAdapter.Update(dataSet, tableName);
                }
            }
            transaction.Commit();
        }
    }
}

The C# documentation states that with a using statement the object within the scope will be disposed and I've seen several places where it's suggested that we don't need to use try/finally clause.

I usually surround my connections with a try/finally, and I always close the connection in the finally clause. Given the above code, is it reasonable to assume that the connection will be closed if there is an exception?

like image 905
Kiril Avatar asked Apr 25 '10 21:04

Kiril


People also ask

Does AC actually cool the air?

Removing heat from the air Believe it or not, creating “cold” isn't actually a thing. Cold is just how we describe a lack of thermal heat. Your air conditioner does not “create” cold air, it removes heat from warm air.

Does using AC use more gas?

Does Your Car's AC Use Gas? In short, yes, but not really enough to matter, according David Bennett, manager of repair systems for the American Automobile Association (AAA). “The AC system, when operating, does add a slight load to the engine, which could slightly increase gas usage,” he says.

How does the AC work in cars?

How Does AC Work in a Car? The air-conditioning system in a car works by manipulating refrigerant between a liquid and a gaseous state. As the refrigerant changes states, it absorbs heat and humidity from the vehicle and allows the system to give off cool, dry air.


3 Answers

You are correct; the using statement compiles to a try / finally block.

The compiler transforms using(resource) statement; into the following code:

{
   ResourceType resource = expression;
   try {
      statement;
   }
   finally {
      if (resource != null) ((IDisposable)resource).Dispose();
   }
}

(The cast to IDisposable is in case ResourceType implements IDisposable explicitly.

like image 53
SLaks Avatar answered Oct 13 '22 01:10

SLaks


Yes, you either need to use a try/finally or a using statement. You don't need both.

A using statement is almost the same as a try/finally except that in C# 3 you can't reassign to the variable inside the using block.

using (IDisposable d = foo())
{
     d = null; // Error:  Cannot assign to 'd' because it is a 'using variable'
}

Previously you could reassign but the original object would still be disposed, not the newly assigned object and you would also get this compile warning:

Possibly incorrect assignment to local 'd' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.

like image 42
Mark Byers Avatar answered Oct 13 '22 00:10

Mark Byers


Yes, the using statement is pretty much just shorthand for a try ... finally block.

For example, this code...

using (MyDisposableType foo = new MyDisposableType())
{
    foo.DoSomething();
}

...would equate to the following...

{
    MyDisposableType foo = new MyDisposableType();
    try
    {
        foo.DoSomething();
    }
    finally
    {
        if (foo != null)
            ((IDisposable)foo).Dispose();
    }
}
like image 20
LukeH Avatar answered Oct 13 '22 01:10

LukeH