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
{
// 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!
*/
Posted Mar 3, 2008, 8:12 PM
Thank you, Alan.
AlanPosted Mar 3, 2008, 6:54 PM
It's just setting a default maximum speed if a Car is created without passing any parameters to the constructor. However, the parameterless constructor is not actually called in this program and so, as you say, the program would execute fine without it.
Perhaps it's used as the basis for other programs on the site where you found the code?
Posted Mar 3, 2008, 5:25 PM
What is the significant of having this step public Car() { maxSpeed = 100; }. Because without this step program is executing well.
Posted Mar 3, 2008, 4:39 PM
Thank you for your explanation, Alan.
AlanPosted Mar 3, 2008, 4:14 PM
I don't think that you can be absolutely certain in what order objects will be destroyed when an application ends (if anyone knows different I'd be happy to be corrected).
However, in all the examples I've seen, the last object created is destroyed first followed by the first object created. Then the remaining objects are destroyed in the order in which they were last created. Here's another example which observes this pattern:
http://www.java2s.com/Tutorial/CSharp/0140__Class/Demonstrateadestructor.htm