Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables with function scope

How the CLR handles local variables with function scope in case an exception is thrown. is it a must to use the finally block or the variable is disposed once the flow leaves the function

below is a small example

    protected void FunctionX()
    {
        List<Employee> lstEmployees;
        try
        {
           lstEmployees= new List<Employee>();
           int s =  lstEmployees[1].ID; // code intended to throw exception
        }
        catch (Exception ex)
        {
            ManageException(ex, ShowMessage); //exception is thrown here
        }
        finally { lstEmployees= null; } // Is the finally block required to make sure the list is cleaned
    }
like image 600
Saber Shebly Avatar asked Sep 17 '26 06:09

Saber Shebly


1 Answers

To answer your specific question, no, the finally block you've listed is not required.

Assigning null to a reference variable does not actually do anything, as garbage collection is non-deterministic. As a simplistic explanation, from time to time, the garbage collector will examine the objects within the heap to determine if there are any active references to them (this is called being "rooted"). If there are no active references, then these references are eligible for garbage collection.

Your assignment to null is not required, as once the function exits, the lstEmployees variable will fall out of scope and will no longer be considered an active reference to the instance that you create within your try block.

There are certain types (both within .NET and in third-party libraries) that implement the IDisposable interface and expose some deterministic cleanup procedures through the Dispose() function. When using these types, you should always call Dispose() when you're finished with the type. In cases where the lifetime of the instance shouldn't extend outside of the lifetime of the function, then you can use a using() { } block, but this is only required if the type implements IDisposable, which List<T> (as you used in your example) does not.

like image 98
Adam Robinson Avatar answered Sep 18 '26 20:09

Adam Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!