Search code examples
.netoopobjectcoding-stylebusiness-logic

Understanding Finally with Object Reference


This might be a duplicate question but i didnt get it on net. I have one function which return type is datatable.

Function a() returns datatable

Dim DtLocLiecence as datatable
try
--- in this part i get value in the datatable

--and i am now returning datatable 

return DtLocLiecence

catch ex

finally

DtLocLiecence = nothing
end try

end function

Now as we know datatable is a reference type that means object a =1 object b if we write b=a then the reference of a got saved in b

so in this case when i am returning the datatable object and in finally if i write that datatable object= nothing then why my returning datatable object didn't got nothing. I am getting proper result but my question is if datatable object reference type then why my datatable not gets nothing in finally.


Solution

  • Give it some thought. When you do DtLocLiecence = nothing, you are nullifying DtLocLiecence and not the actual DataTable object. There is another reference to the actual DataTable that may not be as obvious, i.e. the function itself (through the Return statement), which keeps the DataTable from going out of the scope and thus being collected by the GC.