Understanding Finally with Object Reference

38 views Asked by At

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.

2

There are 2 answers

2
dotNET On BEST ANSWER

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.

2
Joe On

Because the value has already been returned when you set your local reference to null. Perhaps thinking of it as follows might help you understand what's happening, in a hypothetical language where the return value of a function is specified in its argument list:

Function a(ReturnValue result as datatable) 
    Dim DtLocLiecence as datatable
    try
        --- in this part i get value in the datatable

        --and i am now returning datatable 

        result = DtLocLiecence
        return

    catch ex

    finally
        DtLocLiecence = nothing ' No effect on result
    end try


end function