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?

- 543
- 1
- 4
- 5
-
1possible duplicate of [Setting Objects to Null/Nothing after use in .NET](http://stackoverflow.com/questions/2785/setting-objects-to-null-nothing-after-use-in-net) – nawfal Jun 07 '14 at 17:00
8 Answers
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.

- 55,313
- 14
- 116
- 115
-
See my answer below. There's very good reasons for setting members to null in the implementation of Dispose() which could potentially help you avoid bugs. – Mick Jul 12 '19 at 01:17
-
I'm not sure bug-prone is a good argument. If you're using it later on without reading the code in between, the reference could've just as easily been reassigned, or otherwise had its state changed, causing you a different bug for the same reason. Reading **and** understanding the code **before** editing, and testing are the cures for that problem. – xr280xr Oct 13 '20 at 20:27
What matters more IMO is to call Dispose
on objects that implement IDisposable
.
Apart from that, assigning null
to reference variables will just mean that you are explicitly indicating the end of scope — most of the time, it's just a few instructions early (for example, local variables in the method body) — with the 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 a few cases, such as static variables etc, whose scope is application level, you should assign a variable to null
if you are done using it so that object will get garbage collected.
-
3are you saying that the garbage collector will look to see whether a variable is null to decide whether to garbage-collect? I thought it was just whether it was still alive/in-scope. – Craig Johnston Oct 11 '10 at 06:41
-
8This powerpoint presentation http://download.microsoft.com/download/e/2/1/e216b4ce-1417-41af-863d-ec15f2d31b59/DEV490.ppt, slide 30 onwards, shows what the JIT/GC do together. It means the null assignment is particularly pointless. – Damien_The_Unbeliever Oct 11 '10 at 06:50
-
@Damien_The_Unbeliever - a good recource! thanks for that. @Craig, I was actually trying to say that its quite possible that GC will consider a object as garbage even if it is not *apparently* out of scope - all it cares is that if the ref is used or not. So its quite possible that object may get garbage collected even when instance method is running. See this excellent article: http://blogs.msdn.com/b/oldnewthing/archive/2010/08/10/10048149.aspx – VinayC Oct 11 '10 at 08:46
-
1@Craig, continuing on - so its of no use of null assignment for say local variables that are going out of scope. But for static variables that has AppDomain level scope, the object will live till static variable hold the reference. So you may set it null explicitly if you no longer need that object. – VinayC Oct 11 '10 at 08:55
-
@VinayC - I am afraid that what you say is technically incorrect. The scope of a (C#) variable is the section of an application's code where the variable's identifier (name) can be used (ignoring the issue of "access modifiers"). The scope is not affected by `null` assignment. What you are really doing when you are assigning `null` to a variable is *potentially* changing the *lifetime* of the object that the variable refers to. Even the "saying you no longer need the object" is an oversimplification. (You are actually saying you don't need it *here*. You might need it somewhere else!) – Stephen C Jun 19 '22 at 06:57
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.

- 135,331
- 41
- 252
- 292
Most of these responses have the right answer, but for the wrong reasons.
If it's a local variable, the variable will fall off the stack at the end of the method and therefore the object it was pointing to will have one less reference. If that variable was the only reference to the object, then the object is available for GC.
If you set the variable to null (and many who do were taught to do it at the end of the method) then you could actually wind up extending the time the object stays in memory because the CLR will believe that the object can't be collected until the end of the method because it sees a code reference to the object way down there. However, if you omit the setting of null the CLR can determine that no more calls for the object appear after a certain point in your code and, even though the method hasn't completed yet, the GC can collect the object.

- 29,818
- 9
- 60
- 82

- 64,069
- 6
- 49
- 71
Assigning to null is generally a bad idea:
- Conceptually, it's just pointless.
- With many variables, you could have enough extra assignments to null that you appreciably increase the size of the method. The longer the source code for something is, the more mental effort is taken to read it (even if much of it is just stuff that can be filtered out) and the easier it is to spot a bug. Make code more verbose than necessary only when doing so makes it more understandable.
- It is possible that your null assignment won't be optimised away. In that case it's possible that the compiled code won't do the real deallocation until it actually reaches that null assignment, whereas in most cases once the variable is going to do nothing else other than fall out of scope (and sometimes even before) it can be deallocated. You can therefore have a very minor performance impact.
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:
- It is a member of a possibly long-lived object, will no longer be used by that object, and is of considerable size. Here assigning to null is an optimisation.
- It is a member of a possibly long-lived object, will no longer be used by that object, and has therefore been disposed to release its resources. Here assigning to null is a matter of safety as it can be easier to find a case where one accidentally uses a null object than where one accidentally uses a disposed object.
Neither of these cases apply to local variables, only to members, and both are rare.

- 110,372
- 10
- 146
- 251
-
Your second case makes a of sense. Tracking down a null reference exception is easier than tracking down a half disposed object – rollsch Jul 17 '17 at 12:00
-
1@rolls yes, especially since the effect of using such a stale object can be quite far away from the mistaken bit of code. – Jon Hanna Jul 17 '17 at 22:23
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:
{
// Create an object
StringBuilder b = new StringBuilder();
b.Append("asdf");
// Here is the last use of the object:
string x = b.ToString();
// From this point the object can be collected whenever the GC feels like it
// If you assign a null reference to the variable here is irrelevant
b = null;
}

- 687,336
- 108
- 737
- 1,005
-
Does the GC really know which code is being executed? Isn't it just doing a (static) analysis of the stack and following all the references? – Olivier Jacot-Descombes Oct 12 '12 at 18:11
-
@OlivierJacot-Descombes: It does know which variables are used by the code when the garbage collection is done. You can test this by allocating several huge arrays after each other and assign to local variables. The first arrays will be collected to make room for the later ones, eventhough there are variables on the stack having references to them. – Guffa Oct 12 '12 at 18:16
-
+1. You are right. After reading page 35 of the PPT presentation mentioned by Damien_The_Unbeliever I must agree with you. – Olivier Jacot-Descombes Oct 12 '12 at 18:22
For an object which has to implement IDisposable, as a practice I set all members to null in the implementation of IDisposable.
In the distant past I found this practice drastically improved the memory consumption and performance of a .NET Compact Framework application running on Windows Mobile. I think the .NET Compact Framework at the time probably had a very minimalistic implementation of the garbage collector compared to the main .NET Framework and the act of decoupling objects in the implementation of IDisposable helped the GC on the .NET Compact Framework do its thing.
An additional reason for this practice is after IDisposable has been executed on an object, it's actually undesirable for anything to attempt to use any of the members on a disposed object. Sure ideally you'd want an ObjectDisposedException out of an object which has been disposed when something attempts to access any of it's functions, but in place of that a NullReferenceException is better than no exception at all. You want to know about code messing with disposed objects as fooling around with unmanaged resources that have been released is something that can get an application into a lot of trouble.
NOTE: I'm definitely not advocating implementing IDisposable on an object for no other reason than to set members to null. I'm talking about when you need to implement IDisposable for other reasons, i.e. you have members which implement IDisposable or your object wraps unmanaged resources.

- 6,527
- 4
- 52
- 67
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.)

- 10,665
- 10
- 68
- 101