Value Type (ชนิดค่า)
- เก็บข้อมูลโดยตรง (Contains data directly)
- มาจาก
System.ValueType
- จัดเก็บใน Stack
- ตัวอย่าง:
int, char, float, double, bool, struct, enum
- การกำหนดค่า = คัดลอกข้อมูล (Copy by value)
Reference Type (ชนิดอ้างอิง)
- เก็บที่อยู่หน่วยความจำ (Reference to memory location)
- จัดเก็บใน Heap
- ตัวแปรหลายตัวอาจชี้ไปที่ข้อมูลเดียวกัน
- ตัวอย่าง:
class, string, array, delegate, object, dynamic
- การกำหนดค่า = คัดลอก Reference (Copy by reference)
ตารางเปรียบเทียบ
| คุณสมบัติ | Value Type | Reference Type |
| เก็บใน | Stack | Heap |
| ค่าเริ่มต้น | 0, false, '\0' | null |
| การกำหนดค่า | Copy value | Copy reference |
| Null ได้ไหม | ไม่ได้ (ยกเว้น Nullable) | ได้ |
| Destruction | ทันทีเมื่อออก Scope | Garbage Collector |
ตัวอย่างพฤติกรรม
// Value Type
int a = 10;
int b = a;
b = 20;
Console.WriteLine(a); // 10 (ไม่เปลี่ยน)
// Reference Type
int[] arr1 = {1, 2, 3};
int[] arr2 = arr1;
arr2[0] = 99;
Console.WriteLine(arr1[0]); // 99 (เปลี่ยนเพราะชี้ที่เดียวกัน)