What is a Static Constructor in C #?

I have a couple of questions regarding Static Constructor in C #.

  • What is a Static Constructor and how do they differ from a non-static constructor.
  • How can we use them in our application?

** Edited

public class Test
{
    // Static constructor:
    static Test()
    {
        Console.WriteLine("Static constructor invoked.");
    }

    public static void TestMethod()
    {
       Console.WriteLine("TestMethod invoked.");
    }
}

class Sample
{
    static void Main()
    {
        Test.TestMethod();
    }
}

Output: The static constructor is called. Called TestMethod. Thus, this means that the static constructor will be called once. if we call Test.TestMethod () again; static constructor will not call.


Any pointer or suggestion will be appreciated.  

thank

+3
source share
3 answers

, ONCE . () , .

:

public class A
{
     public static int aStaticVal;
     public int aVal;

     static A() {
         aStaticVal = 50;
     }

     public A() {
         aVal = aStaticVal++;
     }
}

:

A a1 = new A();
A a2 = new A();
A a3 = new A();

static . ( ).

static , , . , static (, ) static.

" ", . , " " , , . - :

public class A {
    public static int a, b;
    static A() {
         A.ResetStaticVariables();
    }
    public static void ResetStaticVariables() {
        a = b = 0;
    }
}
+8

, - . , .

, , .

+2

executed when the class is loaded.

He will print: {

  • hi from static A
  • AND

}

public class A{
  static A{
     print("hi from static A");
  }

  public A() {
    print("A");
  }

  main() {
      new A();
  }
}
+1
source

Source: https://habr.com/ru/post/1781436/


All Articles