Search code examples
c#using-statement

What happens if I called Dispose() before using statement end?


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();
    }
}

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.