Constructor tĩnh được khai báo bằng từ khóa static. Là khối mã đầu tiên thực thi trong một lớp, chỉ chạy một lần trong vòng đời của lớp.
Ví dụ
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("Đây là Constructor Tĩnh");
val1 = 70;
}
public Demo(int val3) {
Console.WriteLine("Đây là Constructor Instance");
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();
}
}
}