Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

vb6

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.

like image 584
George K Avatar asked Dec 14 '22 16:12

George K


1 Answers

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);
   } 
 }
like image 189
Dmitry Bychenko Avatar answered Feb 15 '23 23:02

Dmitry Bychenko