I'm cleaning up some C# code for my company and one thing I've been noticing is that the contractors that built this application keep setting object references to null.
Example:
get {
Object o = new Object(); // create a new object that is accessed by the reference 'o'
try {
// Do something with the object
}
finally {
o = null; // set the reference to null
}
}
From what I understand, the object created still exists. There is a chance it can't be accessed now depending if there are any other references to it, but it will still exist until the GC comes and cleans it up.
Is there any reason to have this in a finally block? Are there any cases where this could possibly create an in-adverted memory leak?
Thanks!
If the reference is an instance variable, then setting it to null makes the object available for GC as long as there are no other references to it. However, if you set an instance variable to null, no other method in the class will be able to access that object using that variable.
Not necessarily. An object becomes eligible for garbage collection when there are no live threads anymore that hold a reference to the object. Explicit nulling is simply the practice of setting reference objects to null when you are finished with them.
Here Foo bar = new Foo(); you created object of Foo and put reference to the variable bar . Here Foo a = bar; and Foo b = bar; you put the reference to the variables a and b . So you have now one object and three variables pointing to him. Here bar = null; you clear the bar variable.
The keyword finally is used to identify a statement or statement block after a try - catch block for execution regardless of whether the associated try block encountered an exception, and executes even after a return statement.
This is dependent on scope.
In your given example, o
is only defined within the scope of the property. So it will be useless. However, say o
was within the scope of the class. Then it MIGHT make sense to denote the state of o
.
As it is currently, it is NOT needed.
If the intent is to have GC collect the object asap, then it's utterly useless.
If the object referenced by o
is not used anywhere after the try
block, it will be elected for collection immediately after it is last used (i.e., before the variable o
goes out of scope, and before it reaches the finally
block).
On a related note, see Lippert's Construction Destruction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With