Mega Code Archive

 
Categories / C# / Class Interface
 

Shows the order in which constructors and destructors are called in a C# program

/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // Order.cs - shows the order in which constructors and destructors //            are called in a C# program. // //            Compile this program with the following command line: //                C:>csc Order.cs // namespace nsOrder {     using System;          public class clsMainOrder     {         static public void Main ()         {             clsLastChild child = new clsLastChild ();             Console.WriteLine ();         }     } // // Declare a base class and have its constructor and destructors // print messages.     class clsBase     {         public clsBase ()         {             Console.WriteLine ("Base class constructor called");         }         ~clsBase ()         {             Console.WriteLine ("Base class destructor called");         }     } // Derive a class from clsBase. Have the constructor and destructor // print messages.     class clsFirstChild : clsBase     {         public clsFirstChild ()         {             Console.WriteLine ("First Child constructor called");         }         ~clsFirstChild ()         {             Console.WriteLine ("First Child destructor called");         }     } // Derive a class from clsFirstChile. Have the constructor and destructor // print messages as well.     class clsLastChild  : clsFirstChild     {         public clsLastChild ()         {             Console.WriteLine ("Last Child constructor called");         }         ~clsLastChild ()         {             Console.WriteLine ("Last Child destructor called");         }     } }