1

So I am taking over an existing project where the previous coder did many funny things.

What I see the most and not really understand is the following block of code

finally
{
   if (conn != null)
   {
       conn.Close();
       ds.Dispose();
   }
}
return ds;

VS2010 isn't complaining, and the project works as intended, however this is bizzare to me.

How can it be disposed and then returned? unless the finally takes place after the return somehow?!

If someone can please explain why this is legal? or any other explanation would be appreciated.

Johan
  • 8,068
  • 1
  • 33
  • 46
  • Is he disposing of conn further up and therefore conn == null? – ChrisBint Jul 03 '12 at 10:18
  • You should go through this thread http://stackoverflow.com/questions/2940629/this-dispose-dont-release-memory-used-by-form-after-closing-it – Habib Jul 03 '12 at 11:00

4 Answers4

3

Its not correct do dispose ds before returing it from method as you will lose information in dataset. Disposing connection in finally block seem perfectly alright but not the dataset ds which has to be returned to calling method yet.

Adil
  • 146,340
  • 25
  • 209
  • 204
1

You are supposed to .Dispose() objects when you no longer need them. Clearly you need the DataSet after you've disposed it in this example, so you should absolutely not dispose it here.

.Dispose() on a DataSet might actually not do anything, which is why the code appears to work. Remember that .Dispose() is meant to close and finalize usage of resources that the garbage collector cannot do, or in order to dispose such resources immediately instead of when the garbage collector kicks in. But you shouldn't rely on .Dispose() on a DataSet not doing anything - there might be circumstances where it does do something. Fix the code.

nos
  • 223,662
  • 58
  • 417
  • 506
0

Like that it seems the ds is disposed when it returns, does it give you any errors when you run the code, if so refactor that code, and //comment the ds.Dispose

JohnnBlade
  • 4,261
  • 1
  • 21
  • 22
0

When you call the Dispose() function you are just flagging the object to be garbage collected, you are not "releasing/destroying" the object right away. That is why the code is working. If that logic doesn't make any sense, you can always do something like this:

try{
    // ... your code
    return ds;
}
catch(Exception x)
{
    // ...  Exception code
}
finally
{
   if (conn != null)
   {
       conn.Close();
       ds.Dispose();
   }
}