Method returns an IDisposable - Should I dispose of the result, even if it's not assigned to anythin
        Posted  
        
            by mjd79
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by mjd79
        
        
        
        Published on 2010-06-14T16:56:52Z
        Indexed on 
            2010/06/14
            17:02 UTC
        
        
        Read the original article
        Hit count: 235
        
This seems like a fairly straightforward question, but I couldn't find this particular use-case after some searching around.
Suppose I have a simple method that, say, determines if a file is opened by some process. I can do this (not 100% correctly, but fairly well) with this:
public bool IsOpen(string fileName)
{
  try
  {
    File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
  }
  catch
  {
    // if an exception is thrown, the file must be opened by some other process
    return true;
  } 
}
(obviously this isn't the best or even correct way to determine this - File.Open throws a number of different exceptions, all with different meanings, but it works for this example)
Now the File.Open call returns a FileStream, and FileStream implements IDisposable.  Normally we'd want to wrap the usage of any FileStream instantiations in a using block to make sure they're disposed of properly.  But what happens in the case where we don't actually assign the return value to anything?  Is it still necessary to dispose of the FileStream, like so:
try
{
  using (File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None));
  { /* nop */ }
}
catch 
{
  return true;
}
Should I create a FileStream instance and dispose of that?
try
{
  using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None));
}
...
Or are these totally unnecessary?  Can we simply call File.Open and not assign it to anything (first code example), and let the GC dispose of it right away?
© Stack Overflow or respective owner