What does Using(.....){...} mean [duplicate] - c#

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Using the using statment in c#
What is the C# Using block and why should I use it?
Just wondering what this means? I've seen lots of tutorials online that have the syntax:
using (SqlCeCommand cmd2 = new SqlCeCommand("SELECT city FROM cities JOIN states ON states.id=cities.state WHERE states.state='" + read.GetString(0) + "'", con))
{
SqlCeDataReader readCities = cmd2.ExecuteReader();
while (readCities.Read())
{
parent.Nodes.Add(readCities.GetString(0));
}
}
Why is it used? I tried searching Google, but it comes up with the 'using' keyword which is used for including dll's and other files.

The using statement
using(var disposableObject = new object_that_implements_IDisposable()) { ... }
is syntactic sugar for code similar to following:
var disposableObject = new object_that_implements_IDisposable()
try
{
...
}
finally
{
if(disposableObject != null)
{
((IDisposable)your_object).Dispose();
}
}
This is only applicable for classes that implement IDisposable. It is helpful for cleaning up code where you have objects that take, for example, system resources (file handles, database connections, sockets, etc.) that need to be cleaned up after you are done to free the resource for the rest of the system.
In theory, you could leave out the .Dispose() call, but then you would have to wait for the Garbage Collector to free the kept resources. The GC is awesome at knowing when to free objects to reclaim their memory usage, but it has no idea that it needs to free objects to have them give up other system resources. Thus, these critical resources might not be given up until after the GC decides it needs the memory used by the owner. Thus, you definitely want to dispose of your objects when you are done with them (if they are disposable)!
As to why you'd use using over try/finally, it is purely a coder's preference. I prefer using because you can cascade them:
using(var a = new class())
using(var b = new class())
using(var c = new class())
using(var d = new class())
{
...
}
You'd need quite a few more lines of code to do that with try/finally.
using has additional advantages as well. For example, whereas calling x.Dispose directly might throw a NullReferenceException if x is null, using(x) will not.
See also:
Link
Using the using statement in C#
What is the C# Using block and why should I use it?
http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx

The using just instructs the compiler to write code that will call the Dispose method on the variable you're using. Only types that implement 'IDisposable' can be used with using statements.
In your example, cmd2 will be disposed when the code in the {} finishes.

"Defines a scope, outside of which an object or objects will be disposed"
See using statement

using is applied to objects that implement IDisposable. It ensures that, when leaving the using block (whether normally, or via an exception, or whatever), the disposable object's Dispose method is called.

Using statement is defines a scope, that outside of it the object or objects will be disposed.

Using is a cool way of cleaning up resources, it is equivalent to try{}catch{}finally{dispose}. Effective c# has an item on this and I bet you willget 10+ similar answers.
http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660

See http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx
The using statement encapsulates variables inside of it in a scope. When the execution exits the using block, all objects inside of it are disposed from memory. You might see it with DB connections so that when the using block exits the resources allocated to that connection are cleaned up and closed.

The using statement defines a scope in which to use an object which implements the IDisposable interface. The object will be cleaned up once the block has been exited. See:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Related

Why utilize using() when instantiating a class? [duplicate]

This question already has answers here:
What are the uses of "using" in C#?
(29 answers)
Closed 2 years ago.
I have been working with C# ASP.NET MVC5 for a while and I was wondering something.
Why are we utilizing the using() to instantiate a class sometimes?
For an example:
using (CyrptoStream cs = new CryptoStream(PARAMETERS)
{
//SOMETHING
}
or
using (Aes encryptor = Aes.Create()
{
}
How is that different to MyClass myClass = new MyClass()
Thank you.
using cleans up after itself when control leaves the scope block. Use it to ensure Dispose is called on the object that was created in the top line (next to using)
Multiple using blocks can be nested, though the neater form is to see them stacked in a line with only the bottom one having curly brackets
using(X x = new X())
using(Y y = new Y())
using(Z z = new Z())
{
//code here
}
However it comes to be that control leaves the //code here part (return, reaching the end, throwing exception etcp) we can guarantee that x.Dispose(), y.Dispose() and z.Dispose() will be called. Not everything has to be disposed, which is why we don't see using all over the place, but for some things ensuring Dispose is called is highly advisable in order to free up resources. The documentation for whatever library you're using will advise on whether disposing is recommended. Some prime examples in everyday c# use where disposal is recommended are database connections, graphics/gdi drawing, stream writing.. if you're unsure whether to dispose something or not, take a look at it in the object browser and see if it implements IDisposable; if it does then err on the side of caution and dispose it when you're done with it, but don't dispose of anything you didn't create (it's not your job to do so)

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.
}

What is the difference between instantiation using "using" and a simple instantiation

I have been working on some code for a while. And I had a question:
What it the difference between these two codes ?
using (FORM formExemple = new FORM ())
{
formExemple.ShowDialog();
}
and
FORM formExemple = new FORM ();
formExemple.ShowDialog();
using calls the object's Dispose() method to clean up after itself when it's done. It usually handles things like closing open connections and/or freeing up memory. If you instantiate it otherwise, you have to do that manually. You can only use using on objects that implement the IDisposable interface, which ensures that a method Dispose() exists for the object.
The using block is used to automatically dispose of an object that implements IDisposable.
The first gets Dispose() called at the end of the block. The using block will also ensure that the object is properly disposed of in the case of an Exception.
The second doesn't and needs to be handled by the developer when they're sure that they will no longer need the object.
As ever, consult the documentation - either the MSDN C# guide for using statements or the C# specification (it's section 8.13 in the C# 5 specification).
The using statement can only be used with types implementing IDisposable, and it basically makes sure that whatever resource appears in the inital expression (the resource acquisition expression) is disposed at the end of the block, even if an exception is thrown. Your first code snippet is broadly equivalent to:
FORM formExemple = new FORM(); // I hope you don't *really* use these names
try
{
formExemple.ShowDialog();
}
finally
{
formExemple.Dispose();
}
There's a little bit more to it than that, mind you:
The scope of any variable declared in the resource acquisition expression is the using statement itself
It copes with null values
It copes with changes to the variable within the using statement (the original value is still disposed)
Basically, it makes it easier to clean-up resources which require timely disposal - network streams, file handles, database connections, graphics objects etc.
using is something you can use with objects that have implement the IDisposable interface. The reason to use using is once you are done with your form, you don't have to worry about any clean up, the Dispose method on Form will be called and everything will be cleaned up.
In your second example, Dispose is never called and the objects are still in memory and could be for awhile if the garbage collector doesn't recognize that it needs to clean it up.
The using-statement ...
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
... is a syntactic shortcut (syntactic sugar) for the following pattern:
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
(I took the the example from the link above)
... and therefore the difference between your two code-snippets the try + the call to IDisposable.Dispose() in the finally-block.
The using statement defines the scope for formExemple, the memory allocated for formExemple will be freed once outside the control of the using statement.

Usage of a using statement [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Which is better, and when: using statement or calling Dispose() on an IDisposable in C#?
When should I use “using” blocks in C#?
using a using if statement?
Properly, how will I use a using statement? I have a tutorial open and i do not understand it. And i can see more than 1 different ways to implement. Which is correct or favored way?
The using statement is for any object which implements IDisposable.
using (var my_object = new IDisposableObject ())
{
//do my_object code here.
} //once the program reaches here, it calls my_object.Dispose();
Generally, this is used for objects with connections that manually need to be handled (closed) when the program is finished with them. For example, open connections to files and to the database.
The using statement will call Dispose even if there is an error in the code so it is akin to calling the Dispose method in a finally block of the try catch statement.
Example/Tutorial
It's a shorter syntax to make sure that dispose is called:
using (File f = File.Open("..."))
{
}
is the same as
File f;
try
{
f = File.Open("...");
}
finally
{
f.Dispose();
}
There are 2 fundamental ways you can use the using statement. As extracted from using Directive (C#) from MSDN.
Create an alias for a namespace (a using alias).
Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (a using directive).
Just to expand on Kevin's answer, a using statement effectively wraps your object instantiation in a try/finally block calling the object Dispose() method in the finally section i.e.
using(myObject m = new myObjecyt())
{
// Code here
}
is the same as
myObject m = new myObjecyt()
try
{
// Code here
}
finally
{
m.Dispose();
}
this can be verified by checking the MSIL.
The "Using" keyword helps do a certain thing to be done safely and clearly in .net. This is propertly disposing of certain objects. You may have learned how in .Net we have garbage collection, which means for many object we don't have to care about them when we are done using them. Other object however need to have a method called on them called Dispose. The best practice is that whenever an object has a Dispose method, then we should call that method when we're done with that object.
(They typically handle unmanaged resources. This means that it's using memory or other computer parts that are outside the control of the .NET runtime. So, when garbage collection reaches the discarded .Net object, it is unable to propertly let go of these resources. This can cause memory leaks and all kinds of other problems. A good example is an ADO.NET Connection object. Repeatedly not Disposing of your connection objects can cause DB problems.)
The Using keyword is also tied to this "Dispose" method. It's more accurate to say that when an object has a Dispose method, we either (A.) call .Dispose when we're done with it, or (B.) put our code that uses that object within a Using block. The Using block does several things for you:
When the code moves out of the block, the important Dispose method is automatically called for you.
More importantly, if there is an error in the code block, the Dispose method will still be called. This is why the using block is really helpful. Otherwise you have to put in a lot of error handling code.
The key is that for many of these object that have a Dispose method, error handling is particularly imortant. For a lot our code we don't need error handling; the consequences of an error happening are not really a problem. But for these IDisposable objects errors are often a problem, maybe a big problem. So, .Net provides a syntax for busy developers to add the most basic error handling and move on. Always start off with a Using block at least; maybe later you'll move to fancier error handling, but at least you've got this basic safety.
Here's a good explanation of the Using keyword.

When should I use "using" blocks in C#? [duplicate]

This question already has answers here:
What are the uses of "using" in C#?
(29 answers)
Closed 8 years ago.
Are there particular instances where I should (or shouldn't?) be using "using" blocks:
using(SomeType t = new SomeType()){
...
}
Some objects need some action to be taken when you have finished with them. Usually this is because the object uses some kind of resource that needs to be disposed of. For example, if you have a file object of class File, and this object opens a file from the file system, the file in the file system will need to be closed again.
If you just left the file object, and forgot to call file.Close() it wouldn't be cleaned up until the Garbage Collector (GC) ran and worked out nothing was still using the file object. When the Garbage Collector runs should be left to the Common Language Runtime (CLR) to decide. If the GC doesn't run for quite a while after you have finished with the file, the file could remain open potentially for a long time. This can pose a big problem if there are many file objects, or if something wants to open a file, but can't because the file object you left is still hanging around.
To solve this problem, C# has the IDisposable interface. This has one method called Dispose. Classes that require some cleanup implement this Dispose method. This gives you a standard way for cleaning up any objects that use resources. There are a lot of classes that need to have Dispose called. The problem with this is that code gets covered with calls to Dispose, and they are tricky to follow because the place where you new'ed the object and call Dispose to clean it up are different. So, you had to look around the code a lot and be very careful to check there were calls to Dispose in the right place.
To solve this problem C# introduced the 'using' keyword. You can put a 'using' keyword around where you new an object, and this ensures Dispose will be called on it for you. It guarantees that Dispose will be called whatever happens... even if there is an exception thrown within the body of the using statement.
So, you should use 'using' when you want to be sure an object that allocates resources will be cleaned up.
using can only be used for objects that are declared on the stack, i.e. in a function. It doesn't work for objects that are declared as members of a class. For them, you have to call Dispose yourself. You may have to implement Dispose in your class so that in can call Dispose on any member objects it has that require it.
Common objects that need using called on them are: Files, Database connections, Graphics objects such as Pen and Brush.
Sometimes it is also used when you want two operations to happen together. For example if you want to write a log statement when a block of code is entered and when it exits you could write a log class that you could use like this:
using( Log log = new Log("Doing stuff") )
{
// Stuff
}
The constructor for the log class could be made to write out the message, and the Dispose method could also write it out. Implement the finalizer (~Log) to assert if the Dispose method doesn't get called to ensure the 'using' is remembered around the 'new Log'.
When the SomeType class implements IDisposable.
Use using whenever the type implements IDisposable, unless you're going to wrap it in a try/catch block anyway, then you might as well (depending on what look you prefer) use a finally block.
I see plenty of other answers indicated when you should have a using statement. I want to address when specifically should not have a using statement:
If you need to use your object outside of the scope of the current function, don't have a using block. Good example are a factory method that returns a database connection or a method that needs to return a datareader. In either of those cases if you create your object with a using statement it would be disposed before the method returned, and therefore not usable outside the method.
Now, you still want to be sure that those objects are disposed, so you still might want a using statement somewhere. Just don't include it in the method where the object is actually created. Instead, you can wrap the function call itself in a using statement.
When SomeType implements IDisposable.
That is a clue to you the developer that SomeType uses unmanaged resources that need to be cleaned up.
Example:
using(SqlConnection MyConnection = new SqlConnection("Connection string"))
{
MyConnection.Open();
//...
// 1. SQLConnection is a type that implements IDisposable
// 2. So you can use MyConnection in a using statement
// 3. When using block finishes, it calls Dispose method of
// SqlConnection class
// 4. In this case, it will probably close the connection to
// the database and dispose MyConnection object
}
You can create your own objects that implements IDisposable:
public class MyOwnObjectThatImplementsIDisposable : IDisposable
{
//... some code
public void Dispose()
{
// Put here the code you want to be executed when the
// using statement finish.
}
}
So you could use an object of MyOwnObjectThanImplementsIDisposable type in a using statement:
using(MyOwnObjectThatImplementsIDisposable MyObject = new MyOwnObjectThatImplementsIDisposable)
{
// When the statement finishes, it calls the
// code you´ve writed in Dispose method
// of MyOwnObjectThatImplementsIDisposable class
}
Hope this helps
In this context the using statement is handy for types that implement IDisposable. When the code block exits the scope of the using statement, Dispose() is called implicitly. It's a good habit when working with objects you want to dispose immediately after use.
One specific instance in which you should be careful using a using block is with a WCF Service Client.
As noted in this MSDN article, wrapping a WCF client (which does implement IDisposable) in a using block could mask any errors which result in the client being left in a faulted state (like a timeout or communication problem). Long story short, when Dispose() is called, the client's Close() method fires, but throws and error because it's in a faulted state. The original exception is then masked by the second exception. Not good.
There are various workarounds out there, including one in the MSDN article itself. Others can be found at IServiceOriented and blog.davidbarret.net.
I prefer the last method, myself.
If you want a summary rule. Anytime an object using IDisposable where you would not have a catch, use using. Using, essentially, is this pattern:
try
{
//instantiate and use object
}
finally
{
//dispose object
}
If you do not need a catch, using can save you typing, which is a good thing.
The primary rule is:
* Use USING statement when objects implements IDisposable interface.
This interface provides the Dispose method, which should release the object's resources. If this method is not invoked then the object will stay in memory as long, as CLR wants to perform garbage collection. If the programmer use the USING statement then on the end the object will be disposed, and all resources will be free.
It is very important that all resources that are no longer in use be free as soon as possible.
For more information about it just visit this link: microsoft
Maybe it is worth mentioning that underlying reason for adding “using” lo C# languge is following: some resources can be scarce enough that it doesn’t make sense to wait for GC to call IDisposable. For example, DB connections. If you use try/catch/finally you won’t end up with a dangling connection, but connection will be left hanging until GC doesn’t kick in and this can take a while (if you do not close it explicitly). IF you use "using" (excuse the pun) you will release the connection immediately even if you forgot to close it and even if some exception occured inside the using block.
Another reason, as previous post mentions, is that programmers do not always use finally to clean up. If not using finally in the case of exception you end up with leaking resources…
One situation is when you want to do something at the beginning of a code block, and then undo it at the end of the block, unconditionally (even if there is a throw).
The ctor for the disposable class that you build (and call within the using) would perform the action, and then the Dispose method would undo that action. This is typically how I use it.
Other people has mentioned about "IDisposable" already.
But one of the caveats when using "using" statement is that,
any exceptions thrown within "using" will not be caught
even thought "SomeType" will be disposed regardless.
So in the following snippet,
using (SomeType t = new SomeType()){
throw new Exception("thrown within using");
}
throw new Exception("thrown within using"); should not be disregarded.
I would also add that use a using() statement if something implements IDispose and also if that something you want to dispose of holds on to NON-MANAGED resources like database connections and file handles.
If it's a normal object with say a List<T>, where T is like a Customer object that holds names and address, then you don't need to. The garbage collector is smart enough to manage this for you. But the garbage collector WILL NOT return connections to the connection pool or close file handles.

Categories