C# has two different kinds of constructors, static and instance “ depending on whether they are declared with the static keyword or not. While C# instance constructors are similar to Java constructors, C#'s static constructors are similar to Java static initializers. Static constructors, like their instance counterparts, must have the same name and case as the class of which it is a member. However, unlike instance constructors, static constructors:
Static constructors are automatically invoked before the first static class member is utilized. Here is an example of a static constructor. 1: using System; 2: 3: public class Test{ 4: private static string StaticField; 5: 6: public static void Main(){ 7: Console.WriteLine(Test.StaticField); 8: } 9: 10: // static constructor 11: static Test(){ 12: StaticField = "i am initialized"; 13: Console.WriteLine("running static constructor"); 14: } 15: } Output: c:\expt>test running static constructor i am initialized In the example above, even if lines 4 and 12 are commented out, the output still indicates that the static constructor has executed (output shows 'running static constructor' ). The reason? [6] Well, because Main itself is static, and is considered to be a static member. When Main runs, the static constructor of the class of which it is a member needs to run first.
A static constructor is executed before an instance constructor when a new instance of the class is created, regardless of whether the class has any static member or not. The following example demonstrates this. 1: using System; 2: 3: class Test{ 4: public static void Main(){ 5: Demo d = new Demo(); 6: } 7: } 8: 9: class Demo{ 10: // static constructor 11: static Demo(){ 12: Console.WriteLine("running static constructor"); 13: } 14: // instance constructor 15: public Demo(){ 16: Console.WriteLine("running instance constructor"); 17: } 18: } Output: c:\expt>test running static constructor running instance constructor Like JavaBoth Java static initializers and C# static constructors cannot be called explicitly. Both do not take in parameters, and overloading doesn't make sense in both cases. Unlike Java
|