title: Declaring and disposing a local variable in a function/method in .Net
body: <p>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.</p>
  
  <p>When creating a function/method that creates a local object, which method is best to create and dispose of the object.</p>
  
  <p>For simplicity sake, assume that the method of the object being called will never generate an exception i.e. ConvertThisToString</p>
  
  <pre><code>private string myFirstFunction()
  {
    MyDataType myObject = null;
    try
    {
      myObject = new MyDataType();
      return myOjbect.ConvertThisToString();
    }
    finally
    {
      myObject = null;
    }
   }
  </code></pre>
  
  <p>or </p>
  
  <pre><code>private string mySecondFunction()
  {
    MyDataType myObject = new MyDataType();
    return myOjbect.ConvertThisToString();
  }
  </code></pre>
  
  <p>Are both functions ok and is it just about coding preferences or is there one method that's better than the other? Why?</p>
  
  <p>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. </p>
  
  <p>Should I be using the "using" statement instead?</p>
  
  <p>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.</p>
  
  <p>Thanks for feedback.</p>
  
  <p>Thierry</p>
  
  <p><strong>UPDATED:</strong></p>
  
  <p>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.</p>