At lunch today at TechEd I had a chance to talk to some folks from a Fortune 500 company.  It seems their IT shop is having a debate internally whether they should “null out” all their references when they are done with it.  We had almost the exact some question comes up at a customer meeting right before hand… Two points are enough to create a trend line for me, so I thought I’d write a blog on the topic while I sit outside of Cabana 5 (come on by if you’d like). 

 

No, you don’t need to null out all your managed references.  The GC will free the memory and call the finalizers when the instance goes out of scope.  However, there really two things you should do.

1)       Get educated on some basics of how the GC works. Such as: Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework and Writing Faster Managed Code: Know What Things Cost"

2)       Use perf tools to find out where your real allocation issues are.  There maybe some large, long lived objects that should be nulled out when you are no longer using them. Check out CLRProfiler.

 

 

One pattern these folks mentioned was wrapping an entire function in a try..finally and null resources in the finally… such as:

 

    public static void Foo () {

       string s1;

       object foo;

       try {

          s1 = "foo";

          foo = new Object();

        //do stuff

       } finally {

          s1 = null;

          foo = null;

       }

    }

 

Although try..finally is a good programming practice in general, in this case it is not needed and only adds complexity to your code. The instances will fall out of scope at the end of the method anyway so setting it to null gives no benefit.