/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /* Example6_1.cs illustrates the use of static members */ // declare the Car class class Car { // declare a static field, // numberOfCars stores the number of Car objects private static int numberOfCars = 0; // define the constructor public Car() { System.Console.WriteLine("Creating a Car object"); numberOfCars++; // increment numberOfCars } // define the destructor ~Car() { System.Console.WriteLine("Destroying a Car object"); numberOfCars--; // decrement numberOfCars } // define a static method that returns numberOfCars public static int GetNumberOfCars() { return numberOfCars; } } public class Example6_1 { public static void Main() { // display numberOfCars System.Console.WriteLine("Car.GetNumberOfCars() = " + Car.GetNumberOfCars()); // create a Car object Car myCar = new Car(); System.Console.WriteLine("Car.GetNumberOfCars() = " + Car.GetNumberOfCars()); // create another Car object Car myCar2 = new Car(); System.Console.WriteLine("Car.GetNumberOfCars() = " + Car.GetNumberOfCars()); } }