-1

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?

  • 3
    _scope_ is the difference between the two examples shown. other than that it's a matter of _preference_ on which approach to go with. – Ousmane D. Dec 18 '17 at 16:53
  • @Aominè Apart from scope is any difference how GC will dispose. I had a discussion with technical SME and as per him if it is declared inside try GC will collect the object immediately after execution of try block for disposing. Whereas, if we define outside it will wait for a significant time even after method call is over. I am not fully agreed with him and as per me if I declare outside then as soon as method execution is over it will be collected by GC. – Ravindra Mehta Dec 18 '17 at 16:59
  • 1
    It makes no difference, the GC is smart enough to not be confounded by a declaration. Backgrounder [is here](https://stackoverflow.com/a/17131389/17034). – Hans Passant Dec 18 '17 at 17:05

1 Answers1

5

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.

InBetween
  • 32,319
  • 3
  • 50
  • 90