I have a class with a destructor that I get a null reference exception from because the variable I destroy is sometimes null
.
Is this an appropriate use of the null conditional operator to be in the destructor?
I'm not even sure if this is an appropriate use of a destructor itself since it is not used to dispose of the actual object it's called on but rather a variable of it.
~clsSAPSettings()
{
mtbTemp?.Close();
}
This code was converted from VB6 so I'm trying to figure out how to handle this issue. Any information welcome.
Edit: The class mtbTemp
belongs to implements IDisposable
but doesn't have a finaliser/desctructor. It simply closes a connection used in an ORM model.
For anyone after a detailed explanation I found a great answer, Proper use of the IDisposable interface, it goes into detail about the use of finalizer and how garbage collection actually works.
Please do not use any fields of reference types in the finalizer: the order in which GC (Garbage Collector) collects them is unpredictable and that's why
~clsSAPSettings()
{
mtbTemp?.Close();
}
code can well be performed by GC as followes:
mtbTemp
instancethis
instance:~clsSAPSettings()
mtbTemp?.Close();
i.e. call a method of the collected (destroyed) instanceand you'll have an unstable hard to find error. It seems that you are looking for a IDisposable
interface:
public class clsSAPSettings: IDisposable {
private MyTemp mtbTemp;
...
protected virtual void Dispose(bool disposing) {
if (disposing) {
mtbTemp?.Close();
GC.SuppressFinalize(this);
}
}
public void Dispose() {
Dispose(true);
}
//TODO: do you really want finalizer?
~clsSAPSettings() {
Dispose(false);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With