Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

People also ask

Does using statement Call dispose?

The using declaration calls the Dispose method on the object in the correct way when it goes out of scope. The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned.

Does Dispose get called after exception?

The answer is no. Dispose() does not get called in the attached code. Further more the exception that is thrown is not handled and the program blows up.

Is Dispose method called automatically?

Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.

Why do we have the Dispose () method?

The Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.


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