Static Class ใน C# คือคลาสที่ ไม่สามารถสร้าง Instance ได้ (Cannot be instantiated) และสามารถมีสมาชิกได้เฉพาะ Static Members เท่านั้น Static Class จะเป็น sealed โดยอัตโนมัติ (ไม่สามารถสืบทอดได้) และไม่สามารถมี Instance Constructor ได้
คุณสมบัติของ Static Class
- ประกาศด้วย
static class ClassName - มีได้เฉพาะ Static Members (Fields, Methods, Properties, Events, Constructors)
- ไม่สามารถสร้าง Instance ด้วย
newได้ - เป็น Sealed โดยอัตโนมัติ (ไม่สามารถ Inherit ได้)
- ไม่สามารถมี Instance Constructor ได้ (แต่มี Static Constructor ได้)
- ไม่สามารถ Implement Interface ได้
ตัวอย่าง Static Class
using System;
public static class MathUtils {
// Static Fields
public static float PI = 3.14f;
public static int InstanceCount = 0;
// Static Constructor - รันครั้งเดียวก่อนใช้งานครั้งแรก
static MathUtils() {
Console.WriteLine("MathUtils initialized");
}
// Static Methods
public static int Square(int n) {
return n * n;
}
public static double CircleArea(double radius) {
return PI * radius * radius;
}
}
class Program {
public static void Main(string[] args) {
// เรียกใช้ผ่านชื่อคลาสโดยตรง - ไม่ต้อง new
Console.WriteLine("PI: " + MathUtils.PI); // 3.14
Console.WriteLine("Square: " + MathUtils.Square(3)); // 9
Console.WriteLine("Circle Area: " + MathUtils.CircleArea(2)); // 12.56
}
}
ผลลัพธ์
MathUtils initialized
PI: 3.14
Square: 9
Circle Area: 12.56
Static Members แยกส่วน
// Static Fields
public static float PI = 3.14f;
public static int Square(int n) { return n * n; }
Static Class vs Singleton Pattern
| ด้าน | Static Class | Singleton |
|---|---|---|
| Instance | ไม่มี (Pure Static) | มี Instance เดียว (Lazy/Eager) |
| Inheritance | ไม่ได้ (Sealed) | ได้ (ถ้าไม่ Sealed) |
| Interface | ไม่ได้ | ได้ |
| Lazy Init | ไม่ได้ (Static Constructor) | ได้ |
| Testability | ยาก (Hard to Mock) | ง่ายกว่า (Interface + DI) |
| ใช้เมื่อ | Utility, Extension Methods, Constants | Stateful Service, Database Connection |
Extension Methods - ใช้ Static Class เท่านั้น
public static class StringExtensions {
// this string = Extension method สำหรับ string
public static bool IsNullOrEmpty(this string str) {
return string.IsNullOrEmpty(str);
}
public static string ToTitleCase(this string str) {
return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str);
}
}
// ใช้งานเหมือน Instance Method
string s = "hello world";
Console.WriteLine(s.ToTitleCase()); // Hello World
Best Practices
- ใช้ Static Class สำหรับ **Utility/Helper Methods** ที่ไม่มี State (Stateless)
- ใช้
constหรือreadonlyสำหรับ Constants - หลีกเลี่ยง Static Mutable State (Global State) - ยากต่อ Testing และ Thread Safety
- พิจารณา Dependency Injection + Interface แทน Static Class สำหรับ Business Logic
- Static Constructor ใช้สำหรับ Initialization ที่ซับซ้อนหรืออาจ Throw Exception ได้
Standard Library Static Classes
System.Math- ฟังก์ชันคณิตศาสตร์System.Console- Console I/OSystem.Environment- ข้อมูลระบบSystem.GC- Garbage Collection ControlSystem.Linq.Enumerable- LINQ Extension Methods