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.
Related
Which one do I call?
Is it necessary to call both?
Will the other throw an exception if I have already called one of them?
Close() and Dispose(), when called on a MemoryStream, only serve to do two things:
Mark the object disposed so that future accidental usage of the object will throw an exception.
Possibly1 release references to managed objects, which can make the GC's job a bit easier depending on the GC implementation. (On today's GC algorithms it makes no real difference, so this is a point for an academic discussion and has no significant real-world impact.)
MemoryStream does not have any unmanaged resources to dispose, so you don't technically have to dispose of it. The effect of not disposing a MemoryStream is roughly the same thing as dropping a reference to a byte[] -- the GC will clean both up the same way.
Which one do I call? Is it necessary to call both?
The Dispose() method of streams delegate directly to the Close() method2, so both do exactly the same thing.
Will the other throw an exception if I have already called one of them?
The documentation for IDisposable.Dispose() specifically states it is safe to call Dispose() multiple times, on any object3. (If that is not true for a particular class then that class implements the IDisposable interface in a way that violates its contract, and this would be a bug.)
All that to say: it really doesn't make a huge difference whether you dispose a MemoryStream or not. The only real reason it has Close/Dispose methods is because it inherits from Stream, which requires those methods as part of its contract to support streams that do have unmanaged resources (such as file or socket descriptors).
1 Mono's implementation does not release the byte[] reference. I don't know if the Microsoft implementation does.
2 "This method calls Close, which then calls Stream.Dispose(Boolean)."
3 "If an object's Dispose method is called more than once, the object must ignore all calls after the first one."
None of the above. You needn't call either Close or Dispose.
MemoryStream doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory. The memory will be reclaimed during garbage collection with the rest of the MemoryStream object when your code no longer references the MemoryStream.
If you have a long-lived reference to the MemoryStream, you can set that reference to null to allow the MemoryStream to be garbage collected. Close and Dispose free neither the steam buffer nor the MemoryStream object proper.
Since neither Stream nor MemoryStream have a finalizer, there is no need to call Close or Dispose to cause GC.SuppressFinalize to be called to optimize garbage collection. There is no finalizer to suppress.
The docs for MemoryStream put it this way:
This type implements the IDisposable interface, but does not actually have any resources to dispose. This means that disposing it by directly calling Dispose() or by using a language construct such as using (in C#) or Using (in Visual Basic) is not necessary.
You can use the using block for this. It will automatically call Dispose when it goes outside of its scope.
Example:
using (MemoryStream ms = new MemoryStream())
{
// Do something with ms..
}
// ms is disposed here
Hope this helped.
Use using block so that your object is disposed if its implements IDisposable interface
the following code is Stream.Dispose from reflector as you can see, you don't need to close if you dispose (which is implicit when using using)
public void Dispose()
{
this.Close();
}
Which one do I call?
Any of them.
Is it necessary to call both?
No, either one is sufficient.
Will the other throw an exception if I have already called one of them?
No, disposable pattern declares that subsequent calls to Dispose don't cause negative effects.
Calling Close() will internally call Dispose() to release the resources.
See this link for more information:
msdn
Calling only Dispose() will do the trick =)
In .NET 3.5 (haven't checked other versions), methods are called in the following order when disposing a MemoryStream:
Stream.Dispose()
simply calls Close
Stream.Close()
calls Dispose(true), then GC.SuppressFinalize(this)
MemoryStream.Dispose(true)
sets _isOpen , _writable, and _expandable flags to false
Stream.Dispose(true)
closes async event if active
As a first solution, it's recommended to use using statements wherever possible. This is described here: http://msdn.microsoft.com/en-us/library/yh598w02.aspx
When the lifetime of an IDisposable object is limited to a single method, you should declare and instantiate it in the 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.
Coming to the question now, as others suggested in most .NET framework classes, there is no difference between Close() and Dispose() and it doesn't matter which of the two methods you call. You should call one but not both. However, there are exceptions.
There are exceptions; for example, System.Windows.Forms.Form and System.Data.SqlClient.SqlConnection have different behavior for Close() and Dispose().
For complete details, you can check here: https://blogs.msdn.microsoft.com/kimhamil/2008/03/15/the-often-non-difference-between-close-and-dispose/
Typically I declare streams inside of a using statement to ensure that the stream is properly disposed when I am done with it, and so that I don't mistakenly call it when I'm outside the using block.
Some examples here:
MSDN using Statement Reference
How does one use a using statement with an array of streams?
Would it be equivalent to declare the array outside of a try/catch/finally block and call each stream's dispose method in the finally block?
Lastly, how does one test that the streams have been properly disposed?
I would create a new object that holds the Streams in it. Something like this (not totally fleshed out):
class StreamHolder : IDisposable
{
List<Stream> Streams {get;}
public void Dispose()
{
Streams.ForEach(x=>x.Dispose()):
}
}
This way you can put the container object in the using statment, it will will handle the stream disposal for you. Your other option is the handle it in the Finally block, but if I were going to do this in more than one place, I would like to encapsulate it, so I don't accidentally forget to dispose of all the streams when I am done.
You have to do what using does without using using.
This means looping through the array and calling Dispose on each instance ( after casting explicitly to IDisposable, if needed). Do that loop in the finally block.
Lastly, you don't test for them being properly disposed. Once you call Dispose, you should just null them out, since you can't use them anymore.
The using () statement is a pattern for disposal intended to re-inforce good habits, but it is not required. There are plenty of situations where you need to store objects outside the lifetime of a scoped function.
While I think you should probably architect in a way where you can use the using() statement, the essential thing is that in some encopassing finally block, you dispose each of the streams.
To answer the last question, it does not appear that the Stream class has any method or property to determine if it has been closed/disposed, however if the IDisposable pattern is implemented correctly, you can call Close/Dispose again if you need to be sure.
It seems that in most cases the C# compiler could call Dispose() automatically. Like most cases of the using pattern look like:
public void SomeMethod()
{
...
using (var foo = new Foo())
{
...
}
// Foo isn't use after here (obviously).
...
}
Since foo isn't used (that's a very simple detection) and since its not provided as argument to another method (that's a supposition that applies to many use cases and can be extended), the compiler could automatically and immediately call Dispose() without the developper requiring to do it.
This means that in most cases the using is pretty useless if the compiler does some smart job. IDisposable seem low level enough to me to be taken in account by a compiler.
Now why isn't this done? Wouldn't that improve the performances (if the developpers are... dirty).
A couple of points:
Calling Dispose does not increase performance. IDisposable is designed for scenarios where you are using limited and/or unmanaged resources that cannot be accounted for by the runtime.
There is no clear and obvious mechanism as to how the compiler could treat IDisposable objects in the code. What makes it a candidate for being disposed of automatically and what doesn't? If the instance is (or could) be exposed outside of the method? There's nothing to say that just because I pass an object to another function or class that I want it to be usable beyond the scope of the method
Consider, for example, a factory patter that takes a Stream and deserializes an instance of a class.
public class Foo
{
public static Foo FromStream(System.IO.Stream stream) { ... }
}
And I call it:
Stream stream = new FileStream(path);
Foo foo = Foo.FromStream(stream);
Now, I may or may not want that Stream to be disposed of when the method exits. If Foo's factory reads all of the necessary data from the Stream and no longer needs it, then I would want it to be disposed of. If the Foo object has to hold on to the stream and use it over its lifetime, then I wouldn't want it to be disposed of.
Likewise, what about instances that are retrieved from something other than a constructor, like Control.CreateGraphics(). These instances could exist outside of the code, so the compiler wouldn't dispose of them automatically.
Giving the user control (and providing an idiom like the using block) makes the user's intention clear and makes it much easier to spot places where IDisposable instances are not being properly disposed of. If the compiler were to automatically dispose of some instances, then debugging would be that much more difficult as the developer had to decipher how the automatic disposal rules applied to each and every block of code that used an IDisposable object.
In the end, there are two reasons (by convention) for implementing IDisposable on a type.
You are using an unmanaged resource (meaning you're making a P/Invoke call that returns something like a handle that must be released by a different P/Invoke call)
Your type has instances of IDisposable that should be disposed of when this object's lifetime is over.
In the first case, all such types are supposed to implement a finalizer that calls Dispose and releases all unmanaged resources if the developer fails to do so (this is to prevent memory and handle leaks).
Garbage Collection (while not directly related to IDisposable, is what cleans up unused objects) isn't that simple.
Let me re-word this a little bit. Automatically calling Dispose() isn't that simple. It also won't directly increase performance. More on that a little later.
If you had the following code:
public void DoSomeWork(SqlCommand command)
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
command.Connection = conn;
// Rest of the work here
}
How would the compiler know when you were done using the conn object? Or if you passed a reference to some other method that was holding on to it?
Explicitly calling Dispose() or using a using block clearly states your intent and forces things to get cleaned up properly.
Now, back to performance. Simply calling Dispose() on an Object doesn't guarantee any performance increase. The Dispose() method is used for "cleaning up" resources when you're done with an Object.
The performance increase can come when using un-managed resources. If a managed object doesn't properly dispose of its un-managed resources, then you have a memory leak. Ugly stuff.
Leaving the determination to call Dispose() up to the compiler would take away that level of clarity and make debugging memory leaks caused by un-managed resources that much more difficult.
You're asking the compiler to perform a semantic analysis of your code. The fact that something isn't explicitly referenced after a certain point in the source does not mean that it isn't being used. If I create a chain of references and pass one out to a method, which may or may not store that reference in a property or some other persistent container, should I really expect the compiler to trace through all of that and figure out what I really meant?
Volatile entities may also be a concern.
Besides, using() {....} is more readable and intuitive, which is worth a lot in terms of maintainability.
As engineers or programmers, we strive to be efficient, but that is rarely the same thing as lazy.
Look at the MSDN Artilce for the C# Using Statement The using statement is just a short cut to keep from doing a try and finally in allot of places. Calling the dispose is not a low level functionality like Garbage Collection.
As you can see using is translated into.
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
How would the compiler know where to put the finally block? Does it call it on Garbage Collection?
Garabage Collection doesn't happen as soon as you leave a method. Read this article on Garbage Collection to understand it better. Only after there are no references to the object. A resource could be tied up for much longer than needed.
The thought that keeps popping into my head is that the compiler should not protect developers who do not clean up there resources. Just because a language is managed doesn't mean that it is going to protect from yourself.
C++ supports this; they call it "stack semantics for reference types". I support adding this to C#, but it will require different syntax (changing the semantics based on whether or not a local variable is passed to another method isn't a good idea).
I think that you are thinking about finalizers. Finalizers use the destructor syntax in c#, and they are called automatically by the garbage collector. Finalizers are only appropriate to use when you are cleaning up unmanaged resources.
Dispose is intended to allow for early cleanup of unmanaged resources (and it can be used to clean managed resources as well).
Detection is actually trickier than it looks. What if you have code like this:
var mydisposable = new...
AMethod(mydisposable);
// (not used again)
It's possible that some code in AMethod holds on to a reference to myDisposable.
Maybe it gets assigned to an instance variable inside of that method
Maybe myDisposable subscribes to an event inside of AMethod (then the event publisher holds a reference to myDisposable)
Maybe another thread is spawned by AMethod
Maybe mydisposable becomes "enclosed" by an anonymous method or lamba expression inside of AMethod.
All of those things make it difficult to know for absolute certain that your object is no longer in use, so Dispose is there to let a developer say "ok, I know that it's safe to run my cleanup code now);
Bear in mind also that dispose doesn't deallocate your object -- only the GC can do that. (The GC does have the magic to understand all of the scenarios that I described, and it knows when to clean up your object, and if you really need code to run when the GC detects no references, you can use a finalizer). Be careful with finalizers, though -- they are only for unmanaged allocations that your class owns.
You can read more about this stuff here:
http://msdn.microsoft.com/en-us/magazine/bb985010.aspx
and here: http://www.bluebytesoftware.com/blog/2005/04/08/DGUpdateDisposeFinalizationAndResourceManagement.aspx
If you need unmanaged handle cleanup, read about SafeHandles as well.
It's not the responsibility of the compiler to interpret the scopes in your application and do things like figure out when you no longer need memory. In fact, I'm pretty sure that's an impossible problem to solve, because there's no way for the compiler to know what your program will look like at runtime, no matter how smart it is.
This is why we have the garbage collection. The problem with garbage collection is that it runs on an indeterminate interval, and typically if an object implements IDisposable, the reason is because you want the ability to dispose of it immediately. Like, right now immediately. Constructs such as database connections aren't just disposable because they have some special work to do when they get trashed - it's also because they are scarce.
I seems difficult for the G.C. to know that you won't be using this variable anymore later in the same method. Obviously, if you leave the method, and don't keep a further reference to you variable, the G.C. will dispose it. But using using in you sample, tells the G.C. that you are sure that you will not be using this variable anymore after.
The using statement has nothing to do with performance (unless you consider avoiding resource/memory leaks as performance).
All it does for you is guarantee that the IDisposable.Dispose method is called on the object in question when it goes out of scope, even if an exception has occurred inside the using block.
The Dispose() method is then responsible for releasing any resources used by the object. These are most often unmanaged resources such as files, fonts, images etc, but could also be simple "clean-up" activities on managed objects (not garbage collection however).
Of course if the Dispose() method is implemented badly, the using statement provides zero benefit.
I think the OP is saying "why bother with 'using' when the compiler should be able to work it out magically pretty easily".
I think the OP is saying that
public void SomeMethod()
{
...
var foo = new Foo();
... do stuff with Foo ...
// Foo isn't use after here (obviously).
...
}
should be equivalent to
public void SomeMethod()
{
...
using (var foo = new Foo())
{
... do stuff with Foo ...
}
// Foo isn't use after here (obviously).
...
}
because Foo isn't used again.
The answer of course is that the compiler cannot work it out pretty easily. Garbage Collection (what magically calls "Dispose()" in .NET) is a very complicated field. Just because the symbol isn't being used below that doesn't mean that the variable isn't being used.
Take this example:
public void SomeMethod()
{
...
var foo = new Foo();
foo.DoStuffWith(someRandomObject);
someOtherClass.Method(foo);
// Foo isn't use after here (obviously).
// Or is it??
...
}
In this example, someRandomObject and someOtherClass might both have references to what Foo points out, so if we called Foo.Dispose() it would break them. You say you're just imagining the simple case, but the only 'simple case' where what you're proposing works is the case where you make no method calls from Foo and do not pass Foo or any of its members to anything else - effectively when you don't even use Foo at all in which case you probably have no need to declare it. Even then, you can never be sure that some kind of reflection or event hackery didn't get a reference to Foo just by its very creation, or that Foo didn't hook itself up with something else during its constructor.
In addition to the fine reasons listed above, since the problem can't be solved reliably for all cases, those "easy" cases are something that code analysis tools can and do detect. Let the compiler do stuff deterministically, and let your automatic code analysis tools tell you when you're doing something silly like forgetting to call Dispose.
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.
I have a method, which has a try/catch/finaly block inside. Within the try block, I declare SqlDataReader as follows:
SqlDataReader aReader = null;
aReader = aCommand.ExecuteReader();
In the finally block, the objects which are manually disposed of are those which are set at the class level. So objects in the method which implement IDisposable, such as SqlDataReader above, do they get automatically disposed of? Close() is called on aReader after a while loop executes to get the contents of the reader (which should be Dispose() as that calls Close()). If there is no call to Close(), would this object be closed/disposed of automatically when the method finishes or the object goes out of scope?
EDIT: I am aware of the using statement but there are scenarios which are confusing me.
No, objects are not automatically disposed when they go out of scope.
They're not even guaranteed to be disposed if/when they're garbage-collected, although many IDisposable objects implement a "fallback" finaliser to help ensure that they're eventually disposed.
You are resposible for ensuring that any IDisposable objects are disposed, preferably by wrapping them in a using block.
You should use a using {...} block to wrap your IDisposable objects in - the Dispose() method (which for SqlDataReader passes off to the Close() method) will be called when the using block ends. If you do not use using, the object will not be automatically disposed when it goes out of scope - it will be up to the object finalizer, if it has one, to get rid of resources when it is garbage collected
using (SqlDataReader aReader = aCommand.ExecuteReader())
{
// ... do stuff
} // aReader.Dispose() called here
I agree with all of the above. You should make sure you call Dispose() yourself, and the easiest way to to this is with the using statement (you can also do this yourself in the finally block - this is more verbose, but sometimes necessary). If you don't do this you can find your application leaking unmanaged resources such as handles, or even unmanaged memory, especially if somewhere underneath all of this some COM components are being used, or calls are being made into the Win32 API. This can obviously lead to performance and stability problems, as well as excessive resource usage.
Just because objects that implement IDisposable "should" implement a finaliser that calls their Dispose(bool disposing) method to free unmanaged resources, is no guarantee that this will happen, so you definitely should not rely on it. See, for example, http://msdn.microsoft.com/en-us/library/b1yfkh5e%28VS.71%29.aspx for more information on this point.
Also, something else to bear in mind, is that if your type has members that are disposable, your type should either implement IDisposable (unless the lifecycle of those members is managed by another type, which obviously might get messy), or, if you only use such members in one method, or to implement one particular piece of functionality, you should consider making them local variables/parameters in the methods that use them.
The Dispose pattern doesn't make any guarantees about which objects will call Dispose on which other objects; it may happen sometimes, but you shouldn't care. Instead, it's your responsibility to make sure Dispose() is called for all IDisposable objects. The best way to do that is with the using statement. For example:
using (SqlDataReader aReader = aCommand.ExecuteReader())
{
// your code
}
I am puzzled by the statement "In the finally block, the objects which are manually disposed of are those which are set at the class level." By objects set at the class level, do you mean fields? You probably shouldn't be disposing of these within a ordinary method, because then the life-time of the fields is unpredictable, and depends on which methods you happened to have called. It would be better to implement IDisposable and dispose of fields in your Dispose method.
Might the Using statement help?