Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty "using" block

Tags:

c#

using

It has already been determined here that an empty using block is not an appropriate way to override Dispose(), but what about the following case?

Is this a legitimate use for an empty using block?

try
{
    using (File.OpenRead(sourceFile)) { }
}
catch (FileNotFoundException)
{
    error = "File not found: " + sourceFile;
}
catch (UnauthorizedAccessException)
{
    error = "Not authorized to access file: " + sourceFile;
}
catch (Exception e)
{
    error = "Error while attempting to read file: " + sourceFile + ".\n\n" + e.Message;
}

if (error != null)
    return error;

System.Diagnostics.Process.Start(sourceFile);
like image 817
Dan Bechard Avatar asked Jul 25 '14 14:07

Dan Bechard


1 Answers

No it's not a legitimate use for an empty using block.

You can simply write the try like this:

try
{
    File.OpenRead(sourceFile).Close();
}

Either OpenRead() will succeed and return a stream that you must close (or dispose, but I think .Close() better expresses your intent), or it will thrown an exception and not return anything.

Therefore you can always just close the returned value.

(I assume that you are just checking for read access before doing something else. However, be aware that you could in theory have a race condition because the accessibility of the file could change between you making this check and later on actually opening the file. This is unlikely to happen in practice, but you should be aware of the possibility.)

like image 177
Matthew Watson Avatar answered Oct 20 '22 06:10

Matthew Watson