Pet Peeve: Not «using» IDisposable
I am amazed that I see very little usage of the using statement in c# code. This is a nobrainer for clean code, but continually I see people rolling their own try catch blocks around candidates for using statements.
Take the System.Data.SqlConnection for example. I constantly see alot of the following style of coding:
string connectionString = "your connection string"; SqlConnection cn = null; SqlDataAdapter da = null; DataTable dt = new DataTable();...which is easily rewritten as the following:try{ cn = new SqlConnection(connectionString); da = new SqlDataAdapter("select * from sometable", cn); da.Fill(dt); }finally{ if(cn != null){ cn.Close(); } }
string connectionString = "your connection string"; DataTable dt = new DataTable(); using (SqlConnection cn = new SqlConnection(connectionString)) using (SqlDataAdapter da = new SqlDataAdapter("select * from sometable", cn)){ da.Fill(dt); }The IL that's generated from the using statements looks like this:
.try { IL0014: ldstr "select * from sometable" IL0019: ldloc.2 IL001a: newobj instance void [System.Data]System.Data.SqlClient.SqlDataAdapter::.ctor(string, class [System.Data]System.Data.SqlClient.SqlConnection) IL001f: stloc.3 .try { IL0020: nop IL0021: ldloc.3 IL0022: ldloc.1 IL0023: callvirt instance int32 [System.Data]System.Data.Common.DbDataAdapter::Fill(class [System.Data]System.Data.DataTable) IL0028: pop IL0029: nop IL002a: leave.s IL003e } // end .try finally { IL002c: ldloc.3 IL002d: ldnull IL002e: ceq IL0030: stloc.s CS$4$0000 IL0032: ldloc.s CS$4$0000 IL0034: brtrue.s IL003d IL0036: ldloc.3 IL0037: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL003c: nop IL003d: endfinally } // end handler IL003e: nop IL003f: leave.s IL0053 } // end .try finally { IL0041: ldloc.2 IL0042: ldnull IL0043: ceq IL0045: stloc.s CS$4$0000 IL0047: ldloc.s CS$4$0000 IL0049: brtrue.s IL0052 IL004b: ldloc.2 IL004c: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL0051: nop IL0052: endfinally } // end handlerWhat this means is that by incorporating the using statement in your code the compiler will generate the necessary try...catch blocks to make it work safely.
This is taken from the MS docs on SqlConnection:To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.