Is using the null conditional operator in a destructor bad practice?

  • A+
Category:Languages

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 does implement 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:

  1. Collect mtbTemp instance
  2. Start collecting this instance:
  3. Call ~clsSAPSettings()
  4. Call mtbTemp?.Close(); i.e. call a method of the collected (destroyed) instance

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: