What happens if I call Dispose () before using the end of the statement?

I have this code, I am worried that it is "unsafe", I used Dispose () before the end of use, for me it is a little illogical, but everything works 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(); } } 
+8
c # using-statement
source share
2 answers

The documentation for IDisposable.Dispose states:

If the Dispose method object is called more than once, the object must ignore all calls after the first. An object should not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose may raise an ObjectDisposedException when resources are already located.

Assuming IDisposable implemented correctly, this usage is safe. Dispose will be called a second time and will not do anything a second time.

+14
source share

Well, as @hvd said this use is safe; but this is not recommended if you Fxcop Microsoft Fxcop in your sample code, it will issue a warning / error Fxcop CA2202: Do not dispose objects multiple times

See here

What says

The method implementation contains code paths that can lead to multiple calls to IDisposable.Dispose or Dispose, for example, the Close () method for some types on the same object.

+1
source share

All Articles