Take the 2-minute tour ×

If I got

Dim myRect As Rectangle = New Rectangle(0,0,100,100)

Is it necessary or just fine to later do this:

myRect = Nothing

Or it isn't necessary? Thank you.

IF it is necessary, are there other cases it isn't for my variables?

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

In general, as Joel said, it's unnecessary.

In your specific example, though, it is actually pointless. Rectangle is a value type, so setting it to Nothing is not even affecting an object's reference count; it's assigning a new value (the default value for Rectangle) to your myRect variable. This is analogous to having an Integer variable and setting it to 0 at the end of a method. Doesn't buy you anything.

I should point out that the claim "Setting any variable to Nothing [or null in C#] never accomplishes anything"* is a myth. It is entirely possible that you may have a field in a class which you might as well set to null if the object referenced is no longer needed but you still have a reference to the class instance itself.

As a simplistic example, suppose you had some container class which wraps a T[] array, and you give this container an Empty method. It might make sense to set the container's internal array to null in this method, which would result in zero references to the array object, qualifying it for garbage collection. (You would then create a new array when external code next tried to add a T to the collection.) If you did not set the field to null on Empty, then there would still be a reference to the array (i.e., the field), and so that would be a small amount of memory being used that you really don't need.

Like I said, that's a simplistic example. And honestly, it's rare that you ever need to consider scenarios like that. I just thought I would mention it so that you don't get the wrong impression that setting a field to Nothing literally never accomplishes anything.

*I'm not actually quoting anyone specific here; this is just an over-generalization I've heard stated more than once.

share|improve this answer
What if it was an Image type variable? –  Just Kidding Jan 27 '11 at 19:44
@Omega: Then Joel's answer applies (Image is a reference type). Setting it to null per se is not really valuable. On the other hand, Image implements IDisposable so you should take care to dispose of it properly (by calling Dispose or, better, wrapping the variable in a using block outside of which you no longer need it). –  Dan Tao Jan 27 '11 at 19:46
Thanks then! :D –  Just Kidding Jan 27 '11 at 19:50
add comment

Don't do it. This was important to do in the vb6 days, but for .Net it's possible (though very unlikely) for it to actually throw the garbage collector off and have other unexpected side effects.

share|improve this answer
add comment

Your Answer


