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?
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?
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.
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 toNothing
is not even affecting an object's reference count; it's assigning a new value (the default value forRectangle
) to yourmyRect
variable. This is analogous to having anInteger
variable and setting it to0
at the end of a method. Doesn't buy you anything.I should point out that the claim "Setting any variable to
Nothing
[ornull
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 tonull
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 anEmpty
method. It might make sense to set the container's internal array tonull
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 aT
to the collection.) If you did not set the field to null onEmpty
, 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.