Skip to content

Instantly share code, notes, and snippets.

@benwillkommen
Last active May 9, 2016 15:15
Show Gist options
  • Save benwillkommen/d739c1f943218cd61854332eeb5be440 to your computer and use it in GitHub Desktop.
Save benwillkommen/d739c1f943218cd61854332eeb5be440 to your computer and use it in GitHub Desktop.
using statement v.s. try-catch-finally
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
namespace UsingIlTest
{
public class Class1
{
public Class1()
{
}
public void TryCatchFinally()
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection("fake");
try
{
try
{
SqlCommand cmd = new SqlCommand()
{
CommandText = "SELECT * FROM whatever",
CommandType = CommandType.StoredProcedure,
Connection = conn
};
conn.Open();
(new SqlDataAdapter(cmd)).Fill(ds);
}
catch (Exception exception)
{
}
}
finally
{
conn.Close();
}
}
public void Using()
{
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection("fake"))
{
SqlCommand cmd = new SqlCommand()
{
CommandText = "SELECT * FROM whatever",
CommandType = CommandType.StoredProcedure,
Connection = conn
};
conn.Open();
(new SqlDataAdapter(cmd)).Fill(ds);
conn.Close();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
namespace UsingIlTest
{
public class Class1
{
public void Using()
{
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection("fake"))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM whatever";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
conn.Open();
var adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
conn.Close();
}
}
public void TryCatchFinally()
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection("fake");
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM whatever";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
conn.Open();
var adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
}
catch (Exception)
{
}
finally
{
conn.Close();
}
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null;
this._poolGroup = null;
this.Close();
}
this.DisposeMe(disposing);
base.Dispose(disposing);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment