c# - Variables with function scope -


how clr handles local variables function scope in case exception thrown. must use block or variable disposed once flow leaves function

below small example

    protected void functionx()     {         list<employee> lstemployees;         try         {            lstemployees= new list<employee>();            int s =  lstemployees[1].id; // code intended throw exception         }         catch (exception ex)         {             manageexception(ex, showmessage); //exception thrown here         }         { lstemployees= null; } // block required make sure list cleaned     } 

to answer specific question, no, finally block you've listed not required.

assigning null reference variable not do anything, garbage collection non-deterministic. simplistic explanation, time time, garbage collector examine objects within heap determine if there active references them (this called being "rooted"). if there no active references, these references eligible garbage collection.

your assignment null not required, once function exits, lstemployees variable fall out of scope , no longer considered active reference instance create within try block.

there are types (both within .net , in third-party libraries) implement idisposable interface , expose deterministic cleanup procedures through dispose() function. when using these types, should always call dispose() when you're finished type. in cases lifetime of instance shouldn't extend outside of lifetime of function, can use using() { } block, required if type implements idisposable, list<t> (as used in example) not.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -