Maha

Maha

  • NA
  • 0
  • 328.2k

NP83 Determining Order

Mar 3 2008 11:11 AM

Hi Guys

 

NP83 Determining Order

 

In the following program expected output must be in the following order:

 

In destructor for Car one!

In destructor for Car two!

In destructor for Car three!

In destructor for Car four!

 

But program is giving output in following order:

 

In destructor for Car four!

In destructor for Car one!

In destructor for Car three!

In destructor for Car two!

 

I wish to know how the program is determining the order. Anyone knows please explain.

 

Thank you

 

using System;

 

namespace GCTest

{

   // This car implements IDisposable

   // in order to allow the object

   // user to manually deallocate resources.

   public class Car : IDisposable

   {

      // Internal state data.

      private int currSpeed;

      private int maxSpeed;

      private string petName;

 

      public Car() { maxSpeed = 100; }

 

      public Car(string name, int max, int curr)

      {

         currSpeed = curr;

         maxSpeed = max;

         petName = name;

      }

 

      // Object.Finalize() in disguise!

      // If the object is GC-ed just call the

      ~Car()

      {

         Console.WriteLine("In destructor for {0}!", petName);

      }

           

      // IDisposable impl.

      public void Dispose(){}

   }

 

   public class GCApp

   {

      public static int Main(string[] args)

      {

         // Add these cars to the managed heap.

         Console.WriteLine("*****Adding cars to heap *****");

         Car c1, c2, c3, c4;

 

         c1 = new Car("Car one", 40, 10);

         c2 = new Car("Car two", 70, 5);

         c3 = new Car("Car three", 200, 100);

         c4 = new Car("Car four", 140, 80);

 

         return 0;

      }

   }

}

/*

*****Adding cars to heap *****

In destructor for Car four!

In destructor for Car one!

In destructor for Car three!

In destructor for Car two!

*/


Answers (5)