21243

Multiple using block c#

I am working on application in which i need to access database. Use of using statement is good because "using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens. So i am little bit confused where to use "using" and where to not.

public int route(Route r) { try { using (SqlConnection con = new SqlConnection(connectionString)) { using(SqlCommand com = new SqlCommand("",con)) { using (SqlDataReader sdr = com.ExecuteReader()) { } } } } catch (Exception e) { } }

Answer1:

Any time an object you create implements IDisposable, disposing of it (with or without the using syntactic sugar) is a good idea.

The benefit of the using block syntactic sugar (over manual .Dispose() calls) is that Dispose() will still be called even if there is an exception and flow leaves the using block.

Also, note that you can stack up the usings, without nested indentation:

using (SqlConnection con = new SqlConnection(connectionString)) using(SqlCommand com = new SqlCommand("",con)) using (SqlDataReader sdr = com.ExecuteReader()) // Still need to open connection ... { ...

As an aside, a further benefit of using is that if the IDisposable variable is declared within the using, it that the variable is readonly and cannot be reassigned within the block, e.g.:

using (SqlDataReader sdr = com.ExecuteReader()) { sdr = new SqlDataReader() // Error

Answer2:

This looks okay as far as using blocks are concerned.

However, you should NOT use a try/catch block here, unless you intend on actually doing something with the exception. Otherwise you are just hiding possible errors away, which is dead wrong.

Answer3:

You can simplify it like this:

using (SqlConnection con = new SqlConnection(connectionString)) using(SqlCommand com = new SqlCommand("",con)) using (SqlDataReader sdr = com.ExecuteReader()) { ... }

Using statements are translated to try/finally blocks.Therefore your object will be Disposed even if there is an exception thrown.So if you have a Disposable object and you want to ensure that it will be Disposed after it's used, you can use using statements.Remember it's kind a syntactic sugar for this:

SqlCommand cmd; try { cmd = new SqlCommand(); ... } finally { ((IDisposable)cmd).Dispose(); }

Answer4:

Use the using keyword only when its subject implements the IDisposable interface.

Recommend

  • MVC 3 location allow users in web.config
  • StringBuilder inside large data set this time not store in memory stream inside throug exception out
  • Dynamically add array elements to JSON Object
  • Creating an HTML anchor to run a C# function programatically
  • Getting Transact SQL query result in C# Application
  • How to check if an image exists in an image control with a handler to display the image
  • Putting data from SqlDataReader into HTML table
  • TPL Tasks & Stored procedures
  • how to check if a field is not unique
  • How to get a return value from a stored procedure in VB.NET
  • Reading Excel files in a locale independent way
  • My database system cannot find the file specified in asp.net
  • Servicestack ORMLite/Massive managing multiple DataTables with Expandos / Dynamic?
  • Output from SQL Server and C# different
  • Invalid attempt to read when no data is present in ASP.NET
  • nodejs tls session id
  • Can't connect using mysql_connect to Database in ipage.com hosting?
  • PHP MySQL generating unique random number
  • An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.
  • How can I fix CA2100 Review SQL queries for security vulnerabilities issue
  • Parse returned C# list in AJAX success function
  • ssh2_scp_send() using php corrupts pdf
  • What is using connection in the code
  • PHP PDF generation problem
  • ASP.NET Gridview Paging Problem
  • Align Excel cell to center VB - xlCenter is not declared
  • Imports in __init__.py and `import as` statement
  • Escaping single quotes in JDBC with MySql
  • Iterate twice through a DataReader
  • Adding Parent and Child Nodes in TreeView from Sql Server 2008
  • SqlCommand back up Database
  • Why does it draw lines in the wrong place?
  • Converting a WriteableBitmap image ToArray in UWP
  • Reading JSON from a file using C++ REST SDK (Casablanca)
  • Why value captured by reference in lambda is broken? [duplicate]
  • Getting last autonumber in access
  • javascript inside java/jsp code
  • Android Studio and gradle
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • How can i traverse a binary tree from right to left in java?