ใน C# ทั้ง const และ readonly ใช้สำหรับกำหนดค่าที่ไม่เปลี่ยนแปลง (Immutable) แต่มีความแตกต่างสำคัญ
const
const ประกาศค่าคงที่ที่ทราบค่าตอน Compile-time และไม่เปลี่ยนแปลง ใน C# รองรับเฉพาะ Built-in Types (int, string, double ฯลฯ) User-defined Types (Class, Struct) ไม่สามารถเป็น const ได้ เมธอด Property Event ก็ไม่สามารถเป็น const ได้
ต้องกำหนดค่าในขณะประกาศ:
class Period
{
public const int HOURS = 12;
public const int MINUTES = 60;
}Constants รองรับ Access Modifier ทุกแบบ (private, public, protected, internal, private protected) และทำงานเหมือน static (ค่าเดียวกันทุก Instance) เข้าถึงผ่านชื่อคลาส ไม่ใช่ Instance
readonly
Field ที่เป็น readonly กำหนดค่าได้เฉพาะตอนประกาศหรือใน Constructor หลังสร้าง Instance แล้วแก้ไขไม่ได้
ถ้าเป็น Value Type readonly ทำให้ Immutable แต่ถ้าเป็น Reference Type ยังแก้ไขข้อมูลภายในออบเจกต์ที่อ้างอิงได้ แค่ไม่สามารถเปลี่ยน Reference ไปชี้ออบเจกต์ใหม่ได้
class Person
{
private readonly string _title;
private readonly string _skill;
public Person(string title, string skill)
{
_title = title;
_skill = skill;
}
}readonly field กำหนดค่าได้หลายครั้งใน Declaration และ Constructor ต่างๆ อาจมีค่าแตกต่างตาม Constructor ที่ใช้
ความแตกต่างสำคัญ: Assembly Versioning
- const: ค่า "Baked into" IL ของ Assembly ที่ใช้งาน หากอัปเดต const Assembly ที่ใช้งานยังคงค่าเก่าจนกว่าจะ Recompile
- readonly: เป็น Reference ไปยัง Memory Location ไม่ได้ Baked เข้า IL หาก Memory Location อัปเดต Assembly ที่ใช้งานจะได้ค่าใหม่โดยไม่ต้อง Recompile
ตัวอย่างโค้ด
using System;
class Program
{
static void Main()
{
Console.WriteLine(Period.HOURS); // 12
var person = new Person("John", "Programmer");
person.Print(); // John: Programmer
}
}
class Period
{
public const int HOURS = 12;
public const int MINUTES = 60;
}
class Person
{
private readonly string _title;
private readonly string _skill;
public Person(string title, string skill)
{
_title = title;
_skill = skill;
}
public void Change(string skill)
{
// Error: Cannot assign to readonly field
// _skill = skill;
}
public void Print() => Console.WriteLine($"{_title}: {_skill}");
}ผลลัพธ์
12 John: Programmer