Terry H
Terry H

Reputation: 340

C# using clear dispose

I am reviewing some C# code and it has been a while since I have worked with C#, so I wanted to be sure my instincts are correct. In this code I see a number of places inside a using block where something like the following is done :

using(StreamWriter thing = new StreamWriter()) {

    DataSet DS = SQLQueryMethod();
    do stuff to DS and log that stuff to the a log file using thingy...

    DS.clear();
    DS.Dispose();
}

Now, I have done a little bit of research on this as well as looked back several years through my failing memory and I think there are a number of way to do this that would be better. I would like to know which is the more "standard"/"best pactice" way. I am thinking number 1 below is the best way to do this.

thanks in advance.

  1. Add the DataSet to the using statement so that it gets disposed of automatically with the end of the scope of the using statement, obviating the need for both the clear and dispose. I would do this :

    using(StreamWriter thing = new StreamWriter(), DataSet DS = new DataSet()) {
    
        DS = SQLQueryMethod()
        do stuff to DS{...}
    
    }
    
  2. Just call the dispose on DataSet DS since I think clearing it just prior to a dispose is useless.

  3. It is actually necessary to do it the original way.

Upvotes: 2

Views: 454

Answers (2)

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22054

Correct way is to dispose everything that implements IDisposable - like

using (var thing = new StreamWriter())
using (var ds = SQLQueryMethod())
{
    do stuff to DS {}
} 

Other suggested answers are wrong

using(StreamWriter thing = new StreamWriter())
using(DataSet DS = new DataSet()) 
{
  // this won't compile - DS is in using so it is a read-only variable
  DS = SQLQueryMethod()
  do stuff to DS{...}
} 

Reference: Why is a variable declared in a using statement treated as readonly?

Upvotes: 0

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

Multiple "using statement" can be used as follow:

using (StreamWriter thing = new StreamWriter())
using (DataSet DS = new DataSet())
{
    DS = SQLQueryMethod();
    //do stuff ....
} 

Because StreamWriter and DataSet implements the required Dispose() method in IDisposable interface, no need to explicitly call it afterward

Upvotes: 6

Related Questions