I am attempting to make a simple class that serializes itself to disk when it is no longer in use. The code I have right now (see below). The code I have now seems to work, but I am not fully confident in my knowledge, so I am wondering if anyone else sees any significant problems with this code.
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, this);
byte[] output = Dostuff(ms);
File.WriteAllBytes(DBPATH, output);
}
this.disposed = true;
}
It is virtually impossible to write a finalizer correctly, and doing this sort of work in one is just a recipe for disaster. Not to mention it’ll kill performance and be impossible to debug. Rule 1 for finalizers is don’t ever use them. Rule 2 (for advanced users only) is don’t use them unless you’re really sure you have to.
If it’s just for a fun hobby project then there’s no real harm and it will probably work well enough, but I’d cry if I ever saw something like this in a production codebase.
If you do want to do something like this, then I’d make it an explicit call and simply use the finalizer to catch cases during debugging where the explicit method was not called, e.g.