Defining Static Constructors
Declaration Static Class
- A given class may define only a single static constructor. In other words, the static constructor cannot be overloaded
- A static constructor does not take an access modifier and cannot take any parameters
- A static constructor executes exactly one time, regardless of how many objects of the type are created
- The run-time invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller
- The static constructor executes before any instance-level constructors.
Declaration Static Class
// Static classes can only contain static members! static class TimeUtilClass { public static void PrintTime() { Console.WriteLine(DateTime.Now.ToShortTimeString()); } public static void PrintDate() { Console.WriteLine(DateTime.Today.ToShortDateString()); } }Using Static Class
cannot create an instance of TimeUtilClass using the new keyword static void Main(string[] args) { Console.WriteLine("***** Fun with Static Data *****\n"); // This is just fine. TimeUtilClass.PrintDate(); TimeUtilClass.PrintTime(); // Compiler error! Can't create static classes! TimeUtilClass u = new TimeUtilClass (); ... }The only way to prevent the creation of a class that only exposed static functionality was to either redefine the default constructor using the private keyword or mark the class as an abstract type using the C# abstract keyword
Two ways to prevent the creation of a class class TimeUtilClass2 { // Redefine the default ctor as private to prevent creation. private TimeUtilClass2 (){} ***Way1*** public static void PrintTime() { Console.WriteLine(DateTime.Now.ToShortTimeString()); } public static void PrintDate() { Console.WriteLine(DateTime.Today.ToShortDateString()); } } // Define type as abstract to prevent creation. abstract class TimeUtilClass3 ***Way2*** { public static void PrintTime() { Console.WriteLine(DateTime.Now.ToShortTimeString()); } public static void PrintDate() { Console.WriteLine(DateTime.Today.ToShortDateString()); } }