Disposing Objects Multiple Times - c#

I am a developer that is maintaining and constantly making an application faster and better. I came across a piece of code that uses .Dispose(), which is inside a using statement.
Here is the code:
using (IDbCommand cmd = proxy.Connection.CreateCommand())
{
cmd.CommandText = "usp_GetPluginInfo";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(proxy.Connection.CreateParameter(cmd, "#dealershipId", dealershipId));
cmd.Parameters.Add(proxy.Connection.CreateParameter(cmd, "#pluginId", pluginId));
PluginInfo[] pluginInfos = PopulatePluginsFromCommand(cmd);
result = pluginInfos.First();
cmd.Dispose();
}
Wouldn't the last } Dispose when the Command is finished? I didn't think that it was necessary to use Dispose() in this case.
Thanks for all of your help!

You're right, it's not necessary.
A using statement is translated by the compiler to this:
IDbCommand cmd = proxy.Connection.CreateCommand();
try
{
//...
}
finally
{
if(cmd != null)
((IDisposable)cmd).Dispose();
}
Having said that, calling Dispose more than once should not be "hurtful" either, as a proper IDisposable implementation is supposed to be idempotent. It is, however, redundant, and you should remove it, since you're cleaning up the code.

You are correct! The using block is syntactic sugar for the following:
IDbCommand cmd = proxy.Connection.CreateCommand();
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(proxy.Connection.CreateParameter(cmd, "#dealershipId", dealershipId));
cmd.Parameters.Add(proxy.Connection.CreateParameter(cmd, "#pluginId", pluginId));
PluginInfo[] pluginInfos = PopulatePluginsFromCommand(cmd);
result = pluginInfos.First();}
finally
{
if(cmd != null)
{
((IDisposable)cmd).Dispose();
}
}
So yes, the extra cmd.Dispose(); is unnecessary. In most cases, a well-written class will do nothing the second .Dispose() (using the so-called Disposable Pattern), but sometimes it will cause issues. Get rid of it!

using statement always calls IDisposable.Dispose() method. cmb.Dispose() code is redundant

using calls Dispose upon exit of the block, no matter whether the block is run successfully or an exception occurs. In your example, the explicit call to Dispose is redundant.

There is one reason he could've put it there explicitly. If the IDbCommand isn't the one from System.Data, and the interface that was made for some reason inherited from IDisposable but used new instead of override, they could have different behaviours. But it's 99.999999999% of the time absolutely redundant.

It's redundant and the explicit call to Dispose is not guaranteed to execute. If you want to call Dispose explicitly make sure to do it in a finally block.

The cmd.Dispose(); is unnecessary. In a case where Dispose() is not properly implemented or made to throw the System.ObjectDisposedException, this could be an issue
Refer to the code analysis rule below
The call to CA2202: Do not dispose objects multiple times

Related

C# Singleton in a using statement - what happens to the Singleton at the end of the using statement [duplicate]

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of using?
The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
to
{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}
C# 8 introduces a new syntax, named "using declarations":
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
So the equivalent code of above would be:
using var myRes = new MyResource();
myRes.DoSomething();
And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.
Since a lot of people still do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
//code
}
I guess a lot of people still don't know that you can do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
//code
}
Things like this:
using (var conn = new SqlConnection("connection string"))
{
conn.Open();
// Execute SQL statement here on the connection you created
}
This SqlConnection will be closed without needing to explicitly call the .Close() function, and this will happen even if an exception is thrown, without the need for a try/catch/finally.
using can be used to call IDisposable. It can also be used to alias types.
using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;
using, in the sense of
using (var foo = new Bar())
{
Baz();
}
Is actually shorthand for a try/finally block. It is equivalent to the code:
var foo = new Bar();
try
{
Baz();
}
finally
{
foo.Dispose();
}
You'll note, of course, that the first snippet is much more concise than the second and also that there are many kinds of things that you might want to do as cleanup even if an exception is thrown. Because of this, we've come up with a class that we call Scope that allows you to execute arbitrary code in the Dispose method. So, for example, if you had a property called IsWorking that you always wanted to set to false after trying to perform an operation, you'd do it like this:
using (new Scope(() => IsWorking = false))
{
IsWorking = true;
MundaneYetDangerousWork();
}
You can read more about our solution and how we derived it here.
Microsoft documentation states that using has a double function (https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx), both as a directive and in statements. As a statement, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an IDisposable object. As a directive, it is routinely used to import namespaces and types. Also as a directive, you can create aliases for namespaces and types, as pointed out in the book "C# 5.0 In a Nutshell: The Definitive Guide" (http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8), by Joseph and Ben Albahari. One example:
namespace HelloWorld
{
using AppFunc = Func<IDictionary<DateTime, string>, List<string>>;
public class Startup
{
public static AppFunc OrderEvents()
{
AppFunc appFunc = (IDictionary<DateTime, string> events) =>
{
if ((events != null) && (events.Count > 0))
{
List<string> result = events.OrderBy(ev => ev.Key)
.Select(ev => ev.Value)
.ToList();
return result;
}
throw new ArgumentException("Event dictionary is null or empty.");
};
return appFunc;
}
}
}
This is something to adopt wisely, since the abuse of this practice can hurt the clarity of one's code. There is a nice explanation on C# aliases, also mentioning pros and cons, in DotNetPearls (http://www.dotnetperls.com/using-alias).
I've used it a lot in the past to work with input and output streams. You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose). For example:
using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (System.IO.StreamReader sr = new StreamReader(bs))
{
string output = sr.ReadToEnd();
}
}
}
Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no matter how you exit the using block, it will always dispose the object. This includes returns and exceptions.
using (var db = new DbContext())
{
if(db.State == State.Closed)
throw new Exception("Database connection is closed.");
return db.Something.ToList();
}
It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.
Another great use of using is when instantiating a modal dialog.
Using frm as new Form1
Form1.ShowDialog
' Do stuff here
End Using
You can make use of the alias namespace by way of the following example:
using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;
This is called a using alias directive as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to
e.g.
LegacyEntities.Account
instead of
CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account
or simply
Account // It is not obvious this is a legacy entity
Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.
This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.
In conclusion, when you use a local variable of a type that implements IDisposable, always, without exception, use using1.
If you use nonlocal IDisposable variables, then always implement the IDisposable pattern.
Two simple rules, no exception1. Preventing resource leaks otherwise is a real pain in the *ss.
1): The only exception is – when you're handling exceptions. It might then be less code to call Dispose explicitly in the finally block.
When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.
"using" can also be used to resolve namespace conflicts.
See http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/ for a short tutorial I wrote on the subject.
public class ClassA:IDisposable
{
#region IDisposable Members
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
}
public void fn_Data()
{
using (ClassA ObjectName = new ClassA())
{
// Use objectName
}
}
There are two usages of the using keyword in C# as follows.
As a directive
Generally we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page.
Example:
using System.IO;
As a statement
This is another way to use the using keyword in C#. It plays a vital role in improving performance in garbage collection.
The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.
Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly.
You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.
Example:
string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}
In the preceding code I am not closing any connection; it will close automatically. The using statement will call conn.Close() automatically due to the using statement (using (SqlConnection conn = new SqlConnection(connString)) and the same for a SqlDataReader object. And also if any exception occurs it will close the connection automatically.
For more information, see Usage and Importance of Using in C#.
using is used when you have a resource that you want disposed after it's been used.
For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.
The resource being used needs to implement IDisposable to work properly.
Example:
using (File file = new File (parameters))
{
// Code to do stuff with the file
}
Another example of a reasonable use in which the object is immediately disposed:
using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString))
{
while (myReader.Read())
{
MyObject theObject = new MyObject();
theObject.PublicProperty = myReader.GetString(0);
myCollection.Add(theObject);
}
}
Everything outside the curly brackets is disposed, so it is great to dispose your objects if you are not using them. This is so because if you have a SqlDataAdapter object and you are using it only once in the application life cycle and you are filling just one dataset and you don't need it anymore, you can use the code:
using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
{
// do stuff
} // here adapter_object is disposed automatically
For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.
A different name for error handling would've been nice, and maybe a somehow more obvious one.
It also can be used for creating scopes for Example:
class LoggerScope:IDisposable {
static ThreadLocal<LoggerScope> threadScope =
new ThreadLocal<LoggerScope>();
private LoggerScope previous;
public static LoggerScope Current=> threadScope.Value;
public bool WithTime{get;}
public LoggerScope(bool withTime){
previous = threadScope.Value;
threadScope.Value = this;
WithTime=withTime;
}
public void Dispose(){
threadScope.Value = previous;
}
}
class Program {
public static void Main(params string[] args){
new Program().Run();
}
public void Run(){
log("something happend!");
using(new LoggerScope(false)){
log("the quick brown fox jumps over the lazy dog!");
using(new LoggerScope(true)){
log("nested scope!");
}
}
}
void log(string message){
if(LoggerScope.Current!=null){
Console.WriteLine(message);
if(LoggerScope.Current.WithTime){
Console.WriteLine(DateTime.Now);
}
}
}
}
When you use using, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.
A bullet point:
If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.
The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.
using (Font font2 = new Font("Arial", 10.0f))
{
// Use font2
}
See here for the MSDN article on the C# using keyword.
Not that it is ultra important, but using can also be used to change resources on the fly.
Yes, disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.
The using statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.
The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.
This comes from here.
The using statement tells .NET to release the object specified in the using block once it is no longer needed.
So you should use the 'using' block for classes that require cleaning up after them, like System.IO types.
The Rhino Mocks Record-playback Syntax makes an interesting use of using.
using as a statement automatically calls the dispose on the specified
object. The object must implement the IDisposable interface. It is
possible to use several objects in one statement as long as they are
of the same type.
The CLR converts your code into CIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in CIL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.
The using clause is used to define the scope for the particular variable.
For example:
Using(SqlConnection conn = new SqlConnection(ConnectionString)
{
Conn.Open()
// Execute SQL statements here.
// You do not have to close the connection explicitly
// here as "USING" will close the connection once the
// object Conn goes out of the defined scope.
}

C# SQL Connection try/catch vs using vs try/catch w/ using

I am the third generation to work on a system within my organization and of course there are differences in programming styles. I was wondering what the correct way of connecting to a database is as there are two different styles being used within the system. So whats the "correct" way?
Method 1:
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("StoredProcedure", con))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("foo", bar));
}
using (SqlDataReader reader = command.ExecuteReader())
{
//do stuff
}
}
}
catch (Exception ex)
{
//do stuff
}
Method 2:
// Variables
SqlCommand loComm;
SqlConnection loConn = null;
SqlDataReader loDR;
try
{
// Init command
loComm = new SqlCommand("foo");
loComm.CommandType = CommandType.StoredProcedure;
loComm.Parameters.AddWithValue("foo", bar);
// Init conn
loConn = new SqlConnection(String);
loConn.Open();
loComm.Connection = loConn;
// Run command
loDR = loComm.ExecuteReader();
//do stuff
}
catch (Exception ex)
{
//do stuff
}
While both methods work I am not sure which one is the most appropriate to use. Is there a reason to use one over the other? The second method is cleaner and easier to understand to me, but it doesn't automatically run the iDispose() function when it is finished.
Edit: My question is different then the one suggested, because one approach uses the "using" statement while the other doesn't. So my question is directly related to whether or not to utilize the "using" statements when making a database connection.
Thanks, for all the responses.
Method 2 is simply incorrect and should be repaired.
When completed, you will be left with IDisposable instances that have not been disposed. Most likely, this will play havoc with the connection management that goes on behind the scenes with SqlConnection, especially if this code gets thrashed a lot before GC decides to step in.
If an instance is IDisposable, then it needs to be Disposed of, preferably in the smallest scope possible. Using using will ensure that this happens, even if the code malfunctions and exceptions are thrown.
A using statement:
using(var disposableInstance = new SomeDisposableClass())
{
//use your disposable instance
}
is (give or take a few minor details) syntactic sugar for:
var disposableInstance = new SomeDisposableClass();
try
{
//use your disposable instance
}
finally
{
//this will definitely run, even if there are exceptions in the try block
disposableInstance.Dispose();
}
Even if something goes wrong in the try block, you can be assured that the finally block will execute, thereby ensuring that your disposables are disposed, no matter what happens.
In the first example, if there is an exception thrown, the objects wrapped in the using blocks will be properly closed and disposed.
In the second, you will manually need to dispose of your objects.
One other thing worth mentioning is that if you were planning on disposing of your objects only when an exception is thrown, you will have objects that are not disposed of, so you would need to implement a try..catch..finally and dispose the objects within the finally block.
The first is the better option.
The first one will close the connection if an exception is thrown.
The second one won't, so I'd say go with the first choice.
What the using block does is to warranty that the object Dispose method will always be invoked, no matter if an exception is thrown or not.
Dispose is a method used to clean up resources. In the case of a DB connection, the connection is released, which is really important.
So, the correct way in this case is using the using pattern.
The object included between the using parents mus be IDisposable whic means that it has a Dispose method that should be invoked when the object is no longer needed. If you don't invoke dispose, it will be disposde at any indeterminate time, when the garbage collector destroys the object. That's undesirable in case like a DB connection that must be closed as soon as possible.
The equivalen of usin is a try finally, which includes a call to Dispose within the finally block.
Reading here, it says:
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned. The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
That sounds like the correct way is method 1.

Is SqlCommand.Dispose() required if associated SqlConnection will be disposed?

I usually use code like this:
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
{
var command = connection.CreateCommand();
command.CommandText = "...";
connection.Open();
command.ExecuteNonQuery();
}
Will my command automatically disposed? Or not and I have to wrap it into using block? Is it required to dispose SqlCommand?
Just do this:
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
using(var command = connection.CreateCommand())
{
command.CommandText = "...";
connection.Open();
command.ExecuteNonQuery();
}
Not calling dispose on the command won't do anything too bad. However, calling Dispose on it will suppress the call to the finalizer, making calling dispose a performance enhancement.
The safest policy is to always call Dispose() on an object if it implements IDisposable, either explicitly or via a using block. There may be cases where it is not required but calling it anyway should never cause problems (if the class is written correctly). Also, you never know when an implementation may change meaning that where the call was previously not required it is now definitely required.
In the example you've given, you can add an extra inner using block for the command, as well as maintaining the outer using block for the connection.
Yes, you should, even if it the implementation is currently not doing much, you don't know how it is going to be changed in the future (newer framework versions for instance). In general, you should dispose all objects which implement IDisposable to be on the safe side.
However, if the operation is deferred and you don't control the full scope (for instance when working asynchroneously, or when returning an SqlDataReader or so), you can set the CommandBehavior to CloseConnection so that as soon as the reader is done, the connection is properly closed/disposed for you.
In practice, you can skip Dispose. It doesn't free any resources. It doesn't even suppress finalization since the SQLCommand constructor does that.
In theory, Microsoft could change the implementation to hold an unmanaged resource, but I would hope they'd come out with an API that gets rid of the Component base class long before they'd do that.
You can find out this kind of stuff using Reflector or dotPeek or https://referencesource.microsoft.com/.
I had a small dig (I would suggest that you dig yourself though to be fully sure of the rest of this though as I didn't try that hard) and it looks like when you kill a connection there is no disposal of any children associated with that connection. Furthermore it doesn't actually look like the disposal of a command actually does that much. It will set a field to null, detach itself from a container (this may prevent a managed memory leak) and raise an event (this might be important but I can't see who is listening to this event).
Either way it's good practice to use this stuff in a using block or to ensure you dispose of it using a dispose pattern in the object that holds the connection (if you intend to hold onto the command for a while).
In my opinion, calling Dispose for both SqlConnection and SqlCommand is good practice, use below code
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
try{
using(var command = connection.CreateCommand())
{
command.CommandText = "...";
connection.Open();
command.ExecuteNonQuery();
}
}
catch(Exception ex){ //Log exception according to your own way
throw;
}
finally{
command.Dispose();
connection.Close();
connection.Dispose();
}

Why doesn't 'using' have a catch block?

I understand the point of "using" is to guarantee that the Dispose method of the object will be called. But how should an exception within a "using" statement be handled? If there is an exception, I need to wrap my "using" statement in a try catch. For example:
Lets say there is an exception created in the creation of the object inside the using parameter
try
{
// Exception in using parameter
using (SqlConnection connection = new SqlConnection("LippertTheLeopard"))
{
connection.Open();
}
}
catch (Exception ex)
{
}
Or an Exception within the using scope
using (SqlConnection connection = new SqlConnection())
{
try
{
connection.Open();
}
catch (Exception ex)
{
}
}
It seems like if I already need to handle an exception with a try catch, that maybe I should just handle the disposing of the object as well. In this case the "using" statement doesn't seem to help me out at all. How do I properly handle an exception with "using" statement? Is there a better approach to this that I'm missing?
SqlConnection connection2 = null;
try
{
connection2 = new SqlConnection("z");
connection2.Open();
}
catch (Exception ex)
{
}
finally
{
IDisposable disp = connection2 as IDisposable;
if (disp != null)
{
disp.Dispose();
}
}
Could the "using" keyword syntax be a little more sugary...
It sure would be nice to have this:
using (SqlConnection connection = new SqlConnection())
{
connection.Open();
}
catch(Exception ex)
{
// What went wrong? Well at least connection is Disposed
}
Because you would be 'hiding' extra functionality inside an unrelated keyword.
However you could always write it this way
using (...) try
{
}
catch (...)
{
}
And this way the line represents your intentions -- a using statement that is also a try
using Has nothing to do with error handling. It's shorthand for "call Dispose when you leave this block." Your second code example is perfectly acceptable... why mess with what works?
The using block is just syntactic sugar for a try-finally block. If you need a catch clause, just use a try-catch-finally:
SqlConnection connection;
try
{
connection = new SqlConnection();
connection.Open();
}
catch(Exception ex)
{
// handle
}
finally
{
if (connection != null)
{
connection.Dispose();
}
}
Yes, this is more code than your theoretical "using-catch"; I judge the language developers didn't consider this a very high priority, and I can't say I've ever felt its loss.
I've had places where this would be useful. But more often, when I want to do this it turns out that the problem is in my design; I'm trying to handle the exception in the wrong place.
Instead, I need to allow it to go up to the next level — handle it in the function that called this code, rather than right there.
An interesting idea, but it would make the following kinda confusing:
using (SqlConnection connection = new SqlConnection())
using (SqlCommand cmd = new SqlCommand())
{
connection.Open();
}
catch(Exception ex)
{
// Is connection valid? Is cmd valid? how would you tell?
// if the ctor of either throw do I get here?
}
You are mixing concerns in my opinion. Resource management (i.e. disposale of objects) is completely separated from exception handling. The one-to-one mapping that you describe in your question is just a very special case. Usually exception handling will not happen in the same place as the using scope ends. Or you might have multiple try-catch regions inside a using block. Or ...
I recommend you use example #1 and #2 combined. The reason is your using statement could read a file, for instance, and throw an exception (i.e File Not Found). If you don't catch it, then you have an unhandled exception. Putting the try catch block inside the using block will only catch exceptions that occur after the using statement has executed. A combination of your example one and two is best IMHO.
The purpose of the "using" statement is to ensure that some type of cleanup operation will occur when execution exits a block of code, regardless of whether that exit is via fall-through, an exception, or return. When the block exits via any of those means, it will call Dispose on the parameter of using. The block exists, in some sense, for the benefit of whatever is being specified as the using parameter, and in general that thing won't care why the block was exited.
There are a couple of unusual cases for which provisions might be helpful; their level of additional utility would be well below that provided by having using in the first place (though arguably better than some other features the implementers see fit to provide):
(1) There is a very common pattern in constructors or factories of objects which encapsulate other IDisposable objects; if the constructor or factory exits via an exception, the encapsulated objects should be Disposed, but if it exits via return they should not. Presently, such behavior must be implemented via try/catch, or by combining try/finally with a flag, but it would IMHO be helpful if there were either a variation of using which would only call Dispose when it exited via exception, or else a keep using statement which would null out the temporary employed by the using statement to hold the object which needed disposal (since using cannot be preceded by an identifier, such a feature could be added in a manner somewhat analogous to yield return).
(2) In some cases, it would be helpful if the finally keyword extended to accept an Exception argument; it would hold the exception which caused the guarded clause to exit (if any), or null if the guarded clause exits normally (via return or fall-through), and if the using block could make use of interface IDisposeExOnly {void DisposeEx(Exception ex);} and Interface IDisposeEx : IDisposable, IDisposableExOnly {} (at compile-time, selected DisposeEx() if implemented, or Dispose() otherwise). This could allow transaction-based objects to safely support auto-commit (i.e. perform the commit if the passed-in exception is null, or roll-back if non-null) and would also allow for improved logging in situations where Dispose fails as a consequence of a problem within the guarded clause (the proper thing would be for Dispose to throw an exception which encapsulates both the exception that was pending when it was called, and the exception that occurred as a consequence, but there's presently no clean way to do that).
I don't know if Microsoft will ever add such features; the first, and the first part of the second, would be handled entirely at the language level. The latter part of the second would be at the Framework level.

What are the uses of "using" in C#?

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of using?
The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
to
{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}
C# 8 introduces a new syntax, named "using declarations":
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
So the equivalent code of above would be:
using var myRes = new MyResource();
myRes.DoSomething();
And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.
Since a lot of people still do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
//code
}
I guess a lot of people still don't know that you can do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
//code
}
Things like this:
using (var conn = new SqlConnection("connection string"))
{
conn.Open();
// Execute SQL statement here on the connection you created
}
This SqlConnection will be closed without needing to explicitly call the .Close() function, and this will happen even if an exception is thrown, without the need for a try/catch/finally.
using can be used to call IDisposable. It can also be used to alias types.
using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;
using, in the sense of
using (var foo = new Bar())
{
Baz();
}
Is actually shorthand for a try/finally block. It is equivalent to the code:
var foo = new Bar();
try
{
Baz();
}
finally
{
foo.Dispose();
}
You'll note, of course, that the first snippet is much more concise than the second and also that there are many kinds of things that you might want to do as cleanup even if an exception is thrown. Because of this, we've come up with a class that we call Scope that allows you to execute arbitrary code in the Dispose method. So, for example, if you had a property called IsWorking that you always wanted to set to false after trying to perform an operation, you'd do it like this:
using (new Scope(() => IsWorking = false))
{
IsWorking = true;
MundaneYetDangerousWork();
}
You can read more about our solution and how we derived it here.
Microsoft documentation states that using has a double function (https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx), both as a directive and in statements. As a statement, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an IDisposable object. As a directive, it is routinely used to import namespaces and types. Also as a directive, you can create aliases for namespaces and types, as pointed out in the book "C# 5.0 In a Nutshell: The Definitive Guide" (http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8), by Joseph and Ben Albahari. One example:
namespace HelloWorld
{
using AppFunc = Func<IDictionary<DateTime, string>, List<string>>;
public class Startup
{
public static AppFunc OrderEvents()
{
AppFunc appFunc = (IDictionary<DateTime, string> events) =>
{
if ((events != null) && (events.Count > 0))
{
List<string> result = events.OrderBy(ev => ev.Key)
.Select(ev => ev.Value)
.ToList();
return result;
}
throw new ArgumentException("Event dictionary is null or empty.");
};
return appFunc;
}
}
}
This is something to adopt wisely, since the abuse of this practice can hurt the clarity of one's code. There is a nice explanation on C# aliases, also mentioning pros and cons, in DotNetPearls (http://www.dotnetperls.com/using-alias).
I've used it a lot in the past to work with input and output streams. You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose). For example:
using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (System.IO.StreamReader sr = new StreamReader(bs))
{
string output = sr.ReadToEnd();
}
}
}
Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no matter how you exit the using block, it will always dispose the object. This includes returns and exceptions.
using (var db = new DbContext())
{
if(db.State == State.Closed)
throw new Exception("Database connection is closed.");
return db.Something.ToList();
}
It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.
Another great use of using is when instantiating a modal dialog.
Using frm as new Form1
Form1.ShowDialog
' Do stuff here
End Using
You can make use of the alias namespace by way of the following example:
using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;
This is called a using alias directive as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to
e.g.
LegacyEntities.Account
instead of
CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account
or simply
Account // It is not obvious this is a legacy entity
Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.
This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.
In conclusion, when you use a local variable of a type that implements IDisposable, always, without exception, use using1.
If you use nonlocal IDisposable variables, then always implement the IDisposable pattern.
Two simple rules, no exception1. Preventing resource leaks otherwise is a real pain in the *ss.
1): The only exception is – when you're handling exceptions. It might then be less code to call Dispose explicitly in the finally block.
When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.
"using" can also be used to resolve namespace conflicts.
See http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/ for a short tutorial I wrote on the subject.
public class ClassA:IDisposable
{
#region IDisposable Members
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
}
public void fn_Data()
{
using (ClassA ObjectName = new ClassA())
{
// Use objectName
}
}
There are two usages of the using keyword in C# as follows.
As a directive
Generally we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page.
Example:
using System.IO;
As a statement
This is another way to use the using keyword in C#. It plays a vital role in improving performance in garbage collection.
The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.
Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly.
You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.
Example:
string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}
In the preceding code I am not closing any connection; it will close automatically. The using statement will call conn.Close() automatically due to the using statement (using (SqlConnection conn = new SqlConnection(connString)) and the same for a SqlDataReader object. And also if any exception occurs it will close the connection automatically.
For more information, see Usage and Importance of Using in C#.
using is used when you have a resource that you want disposed after it's been used.
For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.
The resource being used needs to implement IDisposable to work properly.
Example:
using (File file = new File (parameters))
{
// Code to do stuff with the file
}
Another example of a reasonable use in which the object is immediately disposed:
using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString))
{
while (myReader.Read())
{
MyObject theObject = new MyObject();
theObject.PublicProperty = myReader.GetString(0);
myCollection.Add(theObject);
}
}
Everything outside the curly brackets is disposed, so it is great to dispose your objects if you are not using them. This is so because if you have a SqlDataAdapter object and you are using it only once in the application life cycle and you are filling just one dataset and you don't need it anymore, you can use the code:
using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
{
// do stuff
} // here adapter_object is disposed automatically
For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.
A different name for error handling would've been nice, and maybe a somehow more obvious one.
It also can be used for creating scopes for Example:
class LoggerScope:IDisposable {
static ThreadLocal<LoggerScope> threadScope =
new ThreadLocal<LoggerScope>();
private LoggerScope previous;
public static LoggerScope Current=> threadScope.Value;
public bool WithTime{get;}
public LoggerScope(bool withTime){
previous = threadScope.Value;
threadScope.Value = this;
WithTime=withTime;
}
public void Dispose(){
threadScope.Value = previous;
}
}
class Program {
public static void Main(params string[] args){
new Program().Run();
}
public void Run(){
log("something happend!");
using(new LoggerScope(false)){
log("the quick brown fox jumps over the lazy dog!");
using(new LoggerScope(true)){
log("nested scope!");
}
}
}
void log(string message){
if(LoggerScope.Current!=null){
Console.WriteLine(message);
if(LoggerScope.Current.WithTime){
Console.WriteLine(DateTime.Now);
}
}
}
}
When you use using, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.
A bullet point:
If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.
The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.
using (Font font2 = new Font("Arial", 10.0f))
{
// Use font2
}
See here for the MSDN article on the C# using keyword.
Not that it is ultra important, but using can also be used to change resources on the fly.
Yes, disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.
The using statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.
The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.
This comes from here.
The using statement tells .NET to release the object specified in the using block once it is no longer needed.
So you should use the 'using' block for classes that require cleaning up after them, like System.IO types.
The Rhino Mocks Record-playback Syntax makes an interesting use of using.
using as a statement automatically calls the dispose on the specified
object. The object must implement the IDisposable interface. It is
possible to use several objects in one statement as long as they are
of the same type.
The CLR converts your code into CIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in CIL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.
The using clause is used to define the scope for the particular variable.
For example:
Using(SqlConnection conn = new SqlConnection(ConnectionString)
{
Conn.Open()
// Execute SQL statements here.
// You do not have to close the connection explicitly
// here as "USING" will close the connection once the
// object Conn goes out of the defined scope.
}

Categories