Static Methods เป็นสมาชิกของ Class ไม่ใช่ Instance - เรียกใช้ผ่าน Class Name โดยไม่ต้องสร้าง Object
ลักษณะสำคัญ
- เข้าถึงได้เฉพาะ Static Members (Fields/Properties/Methods)
- ไม่สามารถใช้
this,baseได้ - ไม่สามารถเป็น
virtual,abstract,overrideได้ - มีอยู่ก่อนสร้าง Instance ใดๆ
- Thread-safe สำหรับการอ่าน (แต่การเขียนต้อง Sync เอง)
Syntax
public static int GetCount() { return _count; }
ตัวอย่าง
using System;
namespace Demo
{
class StaticVar
{
public static int Num = 0; // Static Field
public void Count() => Num++;
public static int GetNum() => Num; // Static Method
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s = new StaticVar();
s.Count();
s.Count();
s.Count();
// เรียก Static Method ผ่าน Class Name
Console.WriteLine("Variable Num: {0}", StaticVar.GetNum()); // 3
Console.ReadKey();
}
}
}
ผลลัพธ์
Variable Num: 3
Static Constructor
class MyClass
{
static MyClass() // รันครั้งเดียวก่อน Static Member แรกถูกเข้าถึง
{
// Initialize static data
}
}
Static Classes (C# 2.0+)
static class MathUtils
{
public static double PI = 3.14159;
public static double Square(double x) => x * x;
}
// ใช้งาน
double area = MathUtils.PI * MathUtils.Square(5);
ใช้งานจริง
- Utility/Helper Methods:
Math.Sqrt(),String.IsNullOrEmpty() - Factory Methods:
List.Create() - Singleton Pattern
- Extension Methods (ต้องเป็น Static Class + Static Method)