Home  >  Article  >  Backend Development  >  What is a static constructor in C#?

What is a static constructor in C#?

WBOY
WBOYforward
2023-09-04 09:17:02860browse

C# 中的静态构造函数是什么?

A static constructor is a constructor declared using the static modifier. It is the first block of code executed in the class. This way, the static constructor is executed only once during the life cycle of the class.

The following is an example of static constructor in C# -

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Difference {
   class Demo {
      static int val1;
      int val2;

      static Demo() {
         Console.WriteLine("This is Static Constructor");
         val1 = 70;
      }

      public Demo(int val3) {
         Console.WriteLine("This is Instance Constructor");
         val2 = val3;
      }
   
      private void show() {
         Console.WriteLine("First Value = " + val1);
         Console.WriteLine("Second Value = " + val2);
      }

      static void Main(string[] args) {
         Demo d1 = new Demo(110);
         Demo d2 = new Demo(200);
         d1.show();
         d2.show();
         Console.ReadKey();
      }
   }
}

The above is the detailed content of What is a static constructor in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete