Thierry
Thierry

Reputation: 6458

Declaring and disposing a local variable in a function/method in .Net

Until recently it never really bothered me as to how to best declare and dispose of a local variable but I thought I'd ask once and for all and get some feedback as it's starting to bug me more and more these days.

When creating a function/method that creates a local object, which method is best to create and dispose of the object.

For simplicity sake, assume that the method of the object being called will never generate an exception i.e. ConvertThisToString

private string myFirstFunction()
{
  MyDataType myObject = null;
  try
  {
    myObject = new MyDataType();
    return myOjbect.ConvertThisToString();
  }
  finally
  {
    myObject = null;
  }
 }

or

private string mySecondFunction()
{
  MyDataType myObject = new MyDataType();
  return myOjbect.ConvertThisToString();
}

Are both functions ok and is it just about coding preferences or is there one method that's better than the other? Why?

My opinion is that one always requires the try/catch in order to nullify the object, which might be an overkill of try/catch for nullifying's sake, while the other method doesn't call any explicit way to destroy the object, which might be to reliant on .NET GC to release it from memory.

Should I be using the "using" statement instead?

Well, this is probably an incorrect statement. Is a local object immediately destroyed and disposed of when leaving a function or will it be cleared at a later stage by the GC management or other.

Thanks for feedback.

Thierry

UPDATED:

Removed the catch block as it caused confusion in my question. Should haven't been there in the first place since I did say, no error would ever occur.

Upvotes: 1

Views: 8720

Answers (5)

Jay
Jay

Reputation: 10118

You don't need to use a try/catch/finally to set a variable to null. The .NET GC will clear up any unreferenced classes when a method ends in it's own time.

If you are doing something really intensive (more so than your sample shows) then you can set the variable reference to null as a pointer to the GC that this is no longer referenced. This will only make a difference to your program if you are doing something which ends up marking the variable reference for Gen2 collection and then you do more stuff which prevents the GC collecting your variable (because the scope has not been left - in this case the method). This is a bit of an extreme case as the .NET GC is designed to remove this aspect of programming from your daily concern, and regardless, it should get cleared up when the scope ends - it might just a bit longer.

You use 'using' if the referenced object implements IDisposable, and you do this typically to release unmanaged resources - though there may be other reasons why a class implements this interface.

Your first method is total overkill... it should just be as described in MySecondFunction(), and just don't swallow exceptions (I'm referring to the empty catch block) like that - because it leads to buggy, unmaintanable code! :)

Upvotes: 0

T McKeown
T McKeown

Reputation: 12857

As with almost everything, it all depends on what object you are using. If the object you are creating implements IDisposable then you would be best served to place in a using (typically). Outside of that most objects will get cleaned up by the garbage collector. IF you are the producer of a class that accesses COM objects then as the producer you should have provided a away for a proper cleanup, e.g. implement the IDisposable interface and handle the Dispose() correctly. As others have commented swallowing exceptions or even try/catching EVERY method doesn't seem like a reasonable or good idea. If a call you are making has the potential of throwing an exception and you have unmanaged or leaky objects then you should handle via a try/finally or a using (again, if appropriate).

Upvotes: 0

shingonati0n
shingonati0n

Reputation: 157

The best approach here is the Using statement.

something like this:

private string myFirstFunction()
{
  using(MyDataType myObject = new MyDataType())
  {
     return myObject.ConvertThisToString();
  }

}

this will dispose the object after execution.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564433

You don't need to assign to null. When the object leaves scope, it will automatically be eligible for GC. There is no need to do anything special.

Basically, just write the second, simple version.

Should I be using the "using" statement instead?

If your object is wrapping resources (not memory allocated via new ..., but native resources) and implements IDisposable, then yes, you should use the using statement to guarantee those are cleaned up.

Is a local object immediately destroyed and disposed of when leaving a function or will it be cleared at a later stage by the GC management or other.

It will become eligible to be collected. At some point in the future, the GC will clean it up, but the time when this happens in indeterminant.

Upvotes: 2

SLaks
SLaks

Reputation: 887459

That's very wrong.

  • Don't swallow exceptions.

  • Assigning a variable to null at the end of its scope will not help the GC at all.


If your object actually has expensive resources, it should implement IDisposable (correctly!), and you should dispose it using a using statement (but only when you're finished with it!)

Upvotes: 4

Related Questions