Static Constructor

  • A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

  • public class Car {
    	protected static readonly DateTime globalStartTime;
    	protected int RouteNumber {
    		get;
    		set;
    	}
    	static Car() {
    		globalStartTime = DateTime.Now;
    		Console.WriteLine("Static constructor sets global start time to {0}",
    		       globalStartTime.ToLongTimeString());
    	}
    	public Car(int routeNum) {
    		RouteNumber = routeNum;
    		Console.WriteLine("Car #{0} is created.", RouteNumber);
    	}
    	public void Drive() {
    		TimeSpan elapsedTime = DateTime.Now - globalStartTime;
    		Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",
    		           this.RouteNumber,
    		           elapsedTime.TotalMilliseconds,
    		          globalStartTime.ToShortTimeString());
    	}
    }
    class TestCar {
    	static void Main() {
    		Car c1 = new  Car (20);
    		Car c2 = new Car (21);
    		Car1.Drive();
    		System.Threading.Thread.Sleep(25);
    		c2.Drive();
    		System.Console.WriteLine("Press any key to exit.");
    		System.Console.ReadKey();
    	}
    }