Structure (Struct) - Value Type
- Keyword:
struct
- เก็บใน Stack (โดยปกติ)
- Pass by Value (Copy ทั้ง Struct)
- ไม่มี Inheritance (แต่ Implement Interface ได้)
- ไม่มี Destructor/Finalizer
- ไม่มี Parameterless Constructor (Compiler สร้างให้อัตโนมัติ)
- เหมาะสำหรับ: ขนาดเล็ก, Immutable, Value Semantics
Class - Reference Type
- Keyword:
class
- เก็บใน Heap
- Pass by Reference
- รองรับ Inheritance (Single)
- มี Destructor/Finalizer
- มี Parameterless Constructor ได้
- เหมาะสำหรับ: Object ใหญ่, Mutable, Reference Semantics
ตารางเปรียบเทียบ
| คุณสมบัติ | Struct | Class |
| Type Category | Value Type | Reference Type |
| Memory | Stack (mostly) | Heap |
| Assignment | Copy Value | Copy Reference |
| Inheritance | ไม่ได้ (Interface ได้) | ได้ (Single) |
| Default Value | Zero-initialized | null |
| Null Assignment | ไม่ได้ (ต้อง Nullable) | ได้ |
| Destructor | ไม่มี | มี (~ClassName) |
| Interface | Implement ได้ | Implement ได้ |
| Sealed | Implicit Sealed | ระบุได้ |
ตัวอย่าง Struct
public struct Point
{
public int X, Y;
public Point(int x, int y) { X = x; Y = y; }
// Struct Method
public override string ToString() => $"({X}, {Y})";
}
ตัวอย่าง Class
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
// Class สามารถมี Destructor
~Person() { Console.WriteLine("Finalizing..."); }
}
พฤติกรรม Pass by Value vs Reference
// Struct - Copy Value
Point p1 = new Point(1, 2);
Point p2 = p1; // Copy
p2.X = 10;
Console.WriteLine(p1.X); // 1 (ไม่เปลี่ยน)
// Class - Copy Reference
Person per1 = new Person { Name = "John" };
Person per2 = per1; // Same Reference
per2.Name = "Jane";
Console.WriteLine(per1.Name); // "Jane" (เปลี่ยน!)