In C#, is it necessary to assign an object variable to null
if you have finished using it, even when it will go out of scope anyway?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Should you turn off your car before pushing it to the lake?
No. It is a common mistake, but it doesn't make any difference. You aren't setting the object to null, just one reference to it - the object is still in memory, and must still be collected by the garbage collector.
Assigning to null is generally a bad idea:
The only time I would assign something to null to "clear" a variable that will no longer be used, rather than because null is actually a value I explicitly want to assign, is in one of the two possible cases:
Neither of these cases apply to local variables, only to members, and both are rare.
What matters more IMO is to call Dispose on objects that implement IDisposable.
Apart from that, assigning null to reference variables will just means that you are explicitly indicating end of scope - most of times, its just few instruction early (for example, local variables in method body) - with era of compiler/JIT optimizations, its quite possible that runtime would do the same, so you really don;t get anything out of it. In few cases, such as static variables etc (whose scope is application level), you should assign variable to null if you are done using it so that object will get garbage collected.
No. When it comes to local variables it makes no difference at all if you have a reference to the object or not, what matters is if the reference will be used or not.
Putting an extra null assignment in the code doesn't hurt performance much, and it doesn't affect memory management at all, but it will add unmotivated statements to the code that makes it less readable.
The garbage collector knows when the reference is used the last time in the code, so it can collect the object as soon as it's not needed any more.
Example:
I'd just like to add that AFAIK this was only a valid pattern for one point release of Visual Basic, and even that was somewhat debatable. (IIRC it was only for DAO objects.)
No, and that could in fact be dangerous and bug-prone (consider the possibility that someone might try to use it later on, not realizing it had been set to null). Only set something to null if there's a logical reason to set it to null.