Question

I have this code, I am concerned that it is "not safe" I used Dispose() before the using statement end, for me it is slightly illogical, but it works just fine. So, is it safe?

using (FileStream stream = new FileStream(SfilePath, FileMode.Open))
{
    try
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(HighscoresViewModel));
        HVM = deserializer.Deserialize(stream) as HighscoresViewModel;
    }
    catch (InvalidOperationException) 
    {
        stream.Dispose();
        (new FileInfo(SfilePath)).Delete();
        HVM = new HighscoresViewModel();
    }
}
Was it helpful?

Solution

The documentation for IDisposable.Dispose states:

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

Assuming IDisposable is implemented correctly, this use is safe. Dispose will be called a second time, and will do nothing that second time.

OTHER TIPS

Well as said by @hvd that this use is safe; but it's not recommended cause if you implement Microsoft Fxcop on your code sample it will throw an Fxcop warning/error CA2202: Do not dispose objects multiple times

See here

Which says

A method implementation contains code paths that could cause multiple calls to IDisposable.Dispose or a Dispose equivalent, such as a Close() method on some types, on the same object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top