Search code examples
c#datasetdisposetry-catch-finally

is it ok to dispose the dataset in finally block and then returning the dataset?


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.


Solution

  • 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.