Set variables to “Nothing” is a good practice?

拟墨画扇 提交于 2019-12-19 09:15:13

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4820952/set-variables-to-nothing-is-a-good-practice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!