Overhead of creating new SqlConnection in c#
.net, c#, database, sqlconnection
Solution
Yes, it is best practice. The `using` makes your call to Close() exception-safe.
And the overhead of creating a (any) object is indeed minimal, and smallest for short-lived objects (that stay in GC generation 0).
Note that you don't have to call Close() at the end of the using-block anymore, it is automatically done for you (Dispose==Close).
Problem
A while back I wrote an ORM layer for my .net app where all database rows are represented by a subclass of `DatabaseRecord`. There are a number of methods like `Load()`, `Save()` etc. In my initial implementation I created a connection to the DB in the constructor of `DatabaseRecord` e.g. ``` connection = new SqlConnection( ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString ); ``` I then call `Open()` and `Close()` on that SqlConnection at the beginning and end of my methods which access the database. This seemed to me (as someone who was familiar with programming but new to c# and .net) to be the most efficient way to do things - have one connection and open/ close it where necessary within the class. I've just been doing some reading though and it appears that this pattern is recommended in a number of places: ``` using (var connection = new SqlConnection(...)) { connection.Open(); // Stuff with the connection connection.Close(); } ``` I can see why it's desirable - the connection is automatically `Dispose()`d even if the stuff you do in the middle causes an uncaught exception. I was just wondering what the overhead is for calling `new SqlConnection()` potentially many times like this. Connection Pooling is on so I imagine the overhead is minimal and the second approach should be best practice but I just wanted to make sure my assumptions are right.