Home > Backend Development > C#.Net Tutorial > What is a static constructor in C#?

What is a static constructor in C#?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-09-04 09:17:02
forward
906 people have browsed it

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();
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template