Search code examples
c#coding-style

Declaring class object inside try or outside try? Which is best practice


In my code I need to create object of FileInfo/StreamWriter class. It can be done in two ways

FileInfo file = null;
try
{
// now instantiate the object
file = new FileInfo()
}

Or

try
{
FileInfo file =  null;
file = new FileInfo()
}

Which one is better? Is there any difference in the way GC will dispose the object?


Solution

  • It depends. Are you going to need to access file outside your try block? If the answer is "no, not in any case" then declaring it inside the try block is a good idea. If the answer is "yes, in my catch or finally block or somewhere in the code later on", then you should declare it outside the try block.

    As to your question about possible implications in perfomance, forget about the issue already.

    And last but not least, the GC does no dispose anything. Disposing and GC are two unrelated things, the GC has no idea whatsover about disposable objects and the IDisposable interface.