6

Possible Duplicate:
What is the C# Using block and why should I use it?

My question: Is using using(a){do something with a} better than declaring 'a' and using it that way. ie: more secure, faster, ...

see examples for clarification.

Example 1:(without using)

StreamWriter sw;
string line;
sw = new StreamWriter("D:\\NewCon.xml");
sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
sw.WriteLine("<config>");
for (int i = 0; i >=36; i++)
{
    line = "";
    line = "<" + xmlnodes[i] + ">";
    line += vals[i];
    line += "</" + xmlnodes[i] + ">";
    sw.WriteLine(line);   
}
sw.WriteLine("</config>");
sw.Close();
sw.Dispose();    

Example 2:(with using)

string line;    
using (sw = new StreamWriter("D:\\NewCon.xml"))
{
    sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
    sw.WriteLine("<config>");
    for (int i = 0; i >= 36; i++)
    {
        line = "";
        line = "<" + xmlnodes[i] + ">";
        line += vals[i];
        line += "</" + xmlnodes[i] + ">";
        sw.WriteLine(line);
    }
    sw.WriteLine("</config>");
}
Community
  • 1
  • 1
Josef Van Zyl
  • 915
  • 3
  • 19
  • 43

8 Answers8

11

using(a){do something with a}

This means that when the code block is done with a, the program will call a.Dispose. You know that even in the event of an exception, a will have Dispose called. It is essentially doing:

var a = IDisposable_Something;
try{.....}finally{a.Dispose();}

Is it more secure...not really, but that's not the point. The point of it is to make sure that resources which need to be cleaned up are done as soon as the program is finished with them.

So the problem with your first example, is that if somewhere along the line an exception is thrown, it won't make it to the Dispose() method. The second will. You always want to ensure Dispose gets called if it is there, because there is the possibility that the IDisposable classs won't have been written correctly, and it won't have the code to make sure that the unmanaged resources are cleaned up even if Dispose() isn't called (this is generally done in a finalizer). LInk to Dispose Pattern.

The only time I have ever seen where implementing using can be tricky is with the WCF service proxy (and you can work around that issue). There is a bug where if the proxy throws an exception at times, it will cause another exception in the Dispose() method.

http://blogs.msdn.com/b/jjameson/archive/2010/03/18/avoiding-problems-with-the-using-statement-and-wcf-service-proxies.aspx

Other than that you should generally try and put an IDisposable object in a using statement.

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
6

If an exception is thrown in your first example then the resource won't be disposed.

Using using ensures that the resource is disposed even when an exception is thrown.

LukeH
  • 263,068
  • 57
  • 365
  • 409
2

Example 1 should never be done. If an exception is thrown, your Dispose() call will never happen, which could be bad. using guarantees execution of Dispose(). The only good alternative to Example 1 (besides using) would be:

var iDisposableObject = new YourDisposableConstructor();
try
{
    // some code
}
finally
{
    iDisposableObject.Dispose();
}
Dan Herbert
  • 99,428
  • 48
  • 189
  • 219
1

First of all, the code in example 1 should be wrapped in a try/finally block in order to be functionally equivalent with the code in example 2.

That said, I've always liked 'using' blocks for code like this. I think it generally leads to more readable code. As far as security or performance, you're not going to see much difference between example 1 and example 2, providing you use a try/finally block in the first example!

Jesse Taber
  • 2,376
  • 3
  • 23
  • 33
0

It's more secure in the sense that you tend not to forget to dispose of resources, especially in the case of an exception (your code currently doesn't catch any).

It's more succinct and idiomatic since you use less lines of code and the intend of your code becomes much clearer.

So this:

StreamWriter sw;
try
{
sw = new StreamWriter("D:\\epkDATA\\NewCon.xml");
...
}
finally 
{
 sw.Dispose();
}

is equivalent to:

using(StreamWriter sw = new StreamWriter("D:\\epkDATA\\NewCon.xml"))
{
 ...
}
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
0

Using using is safer because you have guaranted resources releasing declared in using(...) braces even when any error or unexpected exit occured.

Przemysław Michalski
  • 9,627
  • 7
  • 31
  • 37
0

Added to previous answers, and the most importabt part, if an exception occurs, calling dispose() is guaranteed.

Xaqron
  • 29,931
  • 42
  • 140
  • 205
0

if ClassA inherit from IDisposing.A "using" pattern is equal to following:

IDisposable iDisposableObject = new YourDisposableConstructor();
try
{
    // some code
}
finally
{
    iDisposableObject.Dispose();
}

so we'd better use the using pattern

Jamiec
  • 133,658
  • 13
  • 134
  • 193
styshoo
  • 111
  • 4