Static Constructor
Static constructor là constructor được khai báo sử dụng modifier static. Nó là khối mã đầu tiên được thực thi trong một class. Với đó, static constructor chỉ thực thi một lần trong vòng đời của class.
Instance Constructor
Instance constructor khởi tạo dữ liệu instance. Instance constructor được gọi khi một đối tượng của class được tạo.
Ví dụ sau cho thấy sự khác biệt giữa static và instance constructor trong C#.
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à Static Constructor");
val1 = 70;
}
public Demo(int val3) {
Console.WriteLine("Đây là Instance Constructor");
val2 = val3;
}
private void show() {
Console.WriteLine("Giá trị đầu tiên = " + val1);
Console.WriteLine("Giá trị thứ hai = " + val2);
}
static void Main(string[] args) {
Demo d1 = new Demo(110);
Demo d2 = new Demo(200);
d1.show();
d2.show();
Console.ReadKey();
}
}
}
Kết quả
Đây là Static Constructor Đây là Instance Constructor Đây là Instance Constructor Giá trị đầu tiên = 70 Giá trị thứ hai = 110 Giá trị đầu tiên = 70 Giá trị thứ hai = 200