Difference between 'using' and scoping? - c#

What is the difference between the following two snippets of code:
using (Object o = new Object())
{
// Do something
}
and
{
Object o = new Object();
// Do something
}
I have started using using a lot more but I am curious as to what the actually benefits are as compared to scoping objects.
Edit: Useful tidbits I took from this:
Jon Skeet:
Note that this does not force garbage collection in any way, shape or form. Garbage collection and prompt resource clean-up are somewhat orthogonal.
Will Eddins comment:
Unless your class implements the IDisposable interface, and has a Dispose() function, you don't use using.

The first snippet calls Dispose at the end of the block - you can only do it with types which implement IDisposable, and it basically calls Dispose in a finally block, so you can use it with types which need resources cleaning up, e.g.
using (TextReader reader = File.OpenText("test.txt"))
{
// Use reader to read the file
}
// reader will be disposed, so file handle released
Note that this does not force garbage collection in any way, shape or form. Garbage collection and prompt resource clean-up are somewhat orthogonal.
Basically, you should use a using statement for pretty much anything which implements IDisposable and which your code block is going to take responsibility for (in terms of cleanup).

At the end of using the object gets disposed (the object you put inside the parenthesis has to implement IDisposable). The object gets disposed also in exception cases. And you do not have to wait for the GC to do it at some time (you control it).
EDIT: The disadvantage of the scoping are:
you do not control the disposition of the object
even if you would call dispose at the end of your scope, it would not be exception safe

Just to literally show the difference...
using (FileStream fileStream = new FileStream("log.txt", FileMode.OpenCreate))
{
//stuff with file stream
}
is the same as...
{
FileStream fileStream = new FileStream("log.txt", FileMode.OpenCreate);
try
{
//stuff with filestream
}
finally
{
if (fileStream != null)
((IDisposable)fileStream).Dispose();
}
}
where as
{
FileStream fileStream = new FileStream("log.txt", FileMode.OpenCreate);
fileStream.Dispose();
}
is as it is.

See the documentation regarding IDisposable and determinable resource deallocation.
Simply put, at the end of the using{} block, you can reliably dispose of allocated resources (e.g. close file handles, database connections etc.)

using just requires an implementation of the IDisposable interface, and calls the Dispose method at the end of the scope.
For plenty of raging arguments about properly disposing objects, there's plenty of other threads.

Related

When do I need the `using` statement for Disposable elements?

I know in the below case, using does its job to release the disposable element, i.e.
using (StreamReader sr = StreamReader(filename))
{
txt = sr.ReadToEnd();
}
However, does the same happen if I use it inline? As you see, there I don't define it as a variable:
txt = (StreamReader(filename)).ReadToEnd();
Defining or not defining a variable doesn't affect whether you need to dispose an object.
If an instance of an class which implements IDisposable is created, you should call Dispose on it when you're finished with it.
You can do that with using or manually calling Dispose - a using statement is usually more convenient and fool-proof.
Firstly, the dispose method exists to allow the developer of the class (in this case System.IO.StreamReader) to release any unmanaged resources they may be holding on to (and a lot of people use it for general cleaning up).
As a rule, if a class implements IDisposable (and therefore contains a Dispose method) it should most definitely be called.
The using statement you have used above would be compiled into the following:
//Very roughly your code sample
using (var sr = new StreamReader())
{
//Some code
}
//What gets spat out by the compiler
var sr = new StreamReader();
try
{
//Some code
}
finally
{
sr.Dispose();
}
As you can see, this pattern means that Dispose will be called regardless of whether the //Some code section throws an exception of not.
Essentially, it's a C# helper so that you don't have to write the safe code above to ensure disposal of disposable objects.
Because of the obvious benefits, the question should really be "When shouldn't you use using".
The same thing does not happen in your second example as is happening in the first example. In your second example, the StreamReader will become eligible for garbage collection immediately after that line executes because you're not storing it in a variable (so it'll go out of scope). The key word here is "eligible" - there's no guarantee of when the object will actually be cleaned up. So the second line of code will result in a lock on the file being "held" until the garbage collector gets around to garbage collecting the StreamReader.
On the other hand, if you call Dispose() on the StreamReader, it'll release the lock on the file immediately without waiting for the garbage collector.

What happens if I called Dispose() before using statement end?

I have this code, I am concerned that it is "not safe"
I used Dispose() before the using statement end, for me it is slightly illogical, but it works just fine. So, is it safe?
using (FileStream stream = new FileStream(SfilePath, FileMode.Open))
{
try
{
XmlSerializer deserializer = new XmlSerializer(typeof(HighscoresViewModel));
HVM = deserializer.Deserialize(stream) as HighscoresViewModel;
}
catch (InvalidOperationException)
{
stream.Dispose();
(new FileInfo(SfilePath)).Delete();
HVM = new HighscoresViewModel();
}
}
The documentation for IDisposable.Dispose states:
If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.
Assuming IDisposable is implemented correctly, this use is safe. Dispose will be called a second time, and will do nothing that second time.
Well as said by #hvd that this use is safe; but it's not recommended cause if you implement Microsoft Fxcop on your code sample it will throw an Fxcop warning/error CA2202: Do not dispose objects multiple times
See here
Which says
A method implementation contains code paths that could cause multiple
calls to IDisposable.Dispose or a Dispose equivalent, such as a
Close() method on some types, on the same object.

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.

Is it better to use the [using] statement in C# or the [dispose] method? Does this apply to external (COM) objects?

What is better, the using directive, or the dispose directive when finished with an object?
using(FileStream fileStream = new FileStream(
"logs/myapp.log",
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.textBoxLogs.Text = streamReader.ReadToEnd();
}
}
On the other hand, when I'm dealing with System.Net.Mail, I'm told I need to Dispose() of the object to release any stray locks.
Is there any consistent guidance? How do I tell what is more appropriate in a given situation for a given object?
The using statement (not directive) involves an implicit call to Dispose(), in a finally block. So there is no contradiction here. Can you link to that discussion?
The official definition of
using (x) { ... }
is
try ... finally if (x != null) x.Dispose(); }
What is better?
From a notational perspective, the using() { } block. Technically they are the same.
It's the same thing. Usage is simple, if you create the object and use it in only one method then use using. If you need to keep it alive beyond the method call then you have to use Dispose().
The runtime callable wrappers for COM objects don't have a Dispose() method.
There's no reason that I can think of to manually call Dispose(), other than in another implementation of Dispose() (for example in a class you've created that implements IDisposable) when you can wrap an object in a using block. The using block puts the creation and disposal of the object in a try/catch/finally block to pretty much gaurantee that the object will be disposed of correctly.
The compiler is more reliable than me. Or you. =)
MSDN documents the using statement and calls out where you can obtain the C# language specification where you can review section 8.13 "The using statement" (at least in the v4.0 reference it's 8.13) that gives a comprehensive explanation of the using statement and how to use it. The fifth paragraph gives the following:
A using statement is translated into
three parts: acquisition, usage, and
disposal. Usage of the resource is
implicitly enclosed in a try statement
that includes a finally clause. This
finally clause disposes of the
resource. If a null resource is
acquired, then no call to Dispose is
made, and no exception is thrown.
using(foo)
{
foo.DoStuff();
}
is just syntactic sugar for this:
try
{
foo.DoStuff();
}
finally
{
if(foo != null)
foo.Dispose();
}
So I'm not sure where the debate comes from. using blocks do call dispose. Most people prefer using blocks when possible as they are cleaner and clearer as to what is going on.
As long as the lifetime of the object is within a block of code, use using, if your object needs to be long lived, for example to be disposed after an asynchronous call you need to manually call Dispose.
A using block is way better than you of remembering the call to Dispose in all possible and impossible ways execution can leave a block of code.
using calls Dispose upon exit. using is better because it assures calling dispose.
using blocks automatically call Dispose() when the end of the block is reached.
There is one really important reason to use the "using statement" anywhere you can.
If the code that wrapped via using statement threw an exception, you could be sure that the "using object" would be disposed.

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