-1

I am not able to figure how will this work:

public Class1 Function1()
{
   DataTable dt;
   try
   {
     dt = new DataTable();
     //.. Do some work
     return new Class2(byref dt);
   }
   finally
   {
      dt.dispose();
   }
}


public Class2(byref DataTable dTable)
{
    this.dataTable = dTable;
}

So, now if I say Class1 obj1 = Function1(); will my obj1.dataTable be disposed? or it will have proper data?

Yogesh
  • 2,198
  • 1
  • 19
  • 28
  • read this http://stackoverflow.com/questions/913228/should-i-dispose-dataset-and-datatable – Nikhil Agrawal May 10 '13 at 01:34
  • @Yogesh - Yes it would be disposed because you call `DataTable.Dispose()` and you pass the `DataTable` as a reference. – Security Hound May 10 '13 at 01:35
  • Technically you should declare and initialize `dt` outside of the `try` block. If the construction fails, you don't want to dispose it, and if it doesn't fail, there's no reason to surround that line in the `try/finally`. (also this is why `using` exists) – Kirk Woll May 10 '13 at 02:05
  • Thanks Nikhil, the link you posted was really resourceful. – Yogesh May 10 '13 at 02:25

1 Answers1

1

yes assuming obj1.dataTable refers to the same object you created inside Function1, it will have been disposed. Finally blocks are always executed, regardless of whether an exception is thrown or not.

Here's some more information on try-finally blocks.

Tejas Sharma
  • 3,420
  • 22
  • 35