Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to set an object to null in the finally block? [duplicate]

Tags:

c#

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!

like image 296
CodyEngel Avatar asked Jul 10 '14 14:07

CodyEngel


People also ask

What does setting an object to null do?

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.

Do null objects require garbage collection?

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.

How do I make an object reference null in Java?

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.

Does finally run after return C#?

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.


2 Answers

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.

like image 171
poy Avatar answered Oct 12 '22 06:10

poy


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.

like image 26
dcastro Avatar answered Oct 12 '22 06:10

dcastro