User-Defined Data Types ใน C# ประกอบด้วย 2 ประเภทหลัก: Structures (Struct) และ Enumerations (Enum)
1. Structure (Struct)
Value Type ที่รวมข้อมูลหลายชนิดไว้ในตัวแปรเดียว ใช้ struct Keyword
คุณสมบัติ Struct
- มี Methods, Fields, Properties, Indexers, Operators, Events ได้
- มี Constructor ได้ (แต่ไม่มี Default Parameterless Constructor)
- ไม่มี Destructor
- ไม่สามารถ Inherit Struct/Class อื่น (แต่ Implement Interface ได้)
- ไม่สามารถเป็น Base Class ให้ Struct/Class อื่น
- Members ไม่สามารถเป็น abstract, virtual, protected
- Pass by Value (Copy ทั้ง Struct)
ตัวอย่าง Struct
public struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x; Y = y;
}
public double DistanceTo(Point other)
{
return Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));
}
}
// ใช้งาน
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
Console.WriteLine(p1.DistanceTo(p2)); // 5
2. Enumeration (Enum)
ชุดค่าคงที่มีชื่อ ใช้ enum Keyword
ตัวอย่าง Enum
public enum Vehicle { Car, Bus, Truck }
public enum Days : byte { Mon=1, Tue, Wed, Thu, Fri, Sat, Sun }
Struct vs Class
| คุณสมบัติ | Struct (Value Type) | Class (Reference Type) |
|---|---|---|
| Memory | Stack (โดยปกติ) | Heap |
| Inheritance | ไม่ได้ (แต่ Implement Interface ได้) | ได้ (Single Inheritance) |
| Null | ไม่ได้ (ยกเว้น Nullable) | ได้ |
| Constructor | ไม่มี Default Parameterless | มี Default ได้ |
| Destructor | ไม่มี | มี (Finalizer) |
| Passing | By Value (Copy) | By Reference |
| Performance | ดีกว่าสำหรับขนาดเล็ก | เหมาะสำหรับ Object ใหญ่ |
เมื่อไหร่ควรใช้ Struct
- ขนาดเล็ก (< 16 bytes)
- Immutable (ค่าไม่เปลี่ยนหลังสร้าง)
- มี Instance เยอะมาก (Memory Pressure)
- Semantic เป็น Value (เช่น Point, DateTime, Decimal)