Type ทั้งหมดใน C# แบ่งได้ 2 ประเภทหลัก: Value Types และ Reference Types
Value Types
Variable ของ Value Type เก็บ Data โดยตรง แต่ละ Variable มี Copy ของ Data เอง ไม่สามารถแก้ไข Object ของ Variable อื่นได้
Value Types ได้แก่:
- Numeric Types: int, float, double ฯลฯ
- char และ bool
- struct
- enum
Value Type เก็บค่าจริง (ไม่ใช่ Pointer เหมือน Reference Type)
สร้าง Custom Value Type ด้วย struct:
public struct Point { public int X; public int Y; }
var p1 = new Point();ใน Memory: Instance ของ Point เก็บค่า X, Y ตรงๆ
การ Assign Value Type สร้าง Copy:
Point p2 = p1; // p2 เป็น Copy ของ p1
p1 และ p2 มี Memory แยกกัน เปลี่ยน p2 ไม่ส่งผล p1
Reference Types
Variable ของ Reference Type เก็บ Reference (ที่อยู่) ของ Object สอง Variable อาจชี้ Object เดียวกัน การเปลี่ยนแปลงผ่าน Variable หนึ่ง ส่งผลต่ออีกตัว
Reference Types ได้แก่:
- String
- Class
- Array
- Delegate
- Interface
ตัวอย่าง Class (Reference Type):
public class Point { public int X; public int Y; }
var p1 = new Point();ใน Memory: Variable p1 เก็บ Address ชี้ Object จริงบน Heap
การ Assign Reference Type Copy แค่ Reference:
Point p2 = p1; // p2 ชี้ Object เดียวกับ p1
เปลี่ยน p2.X จะส่งผล p1.X ด้วย
ตัวอย่างโค้ดเปรียบเทียบ
using System;
class Program
{
static void Main()
{
// Value Type (struct)
var p1 = new Point { X = 10 };
Point p2 = p1;
p2.X = 20;
Console.WriteLine("Value Type");
Console.WriteLine(p1.X); // 10
Console.WriteLine(p2.X); // 20
// Reference Type (class)
var u1 = new User { Age = 10 };
User u2 = u1;
u2.Age = 20;
Console.WriteLine("Reference Type");
Console.WriteLine(u1.Age); // 20
Console.WriteLine(u2.Age); // 20
}
}
public struct Point { public int X; public int Y; }
public class User { public int Age { get; set; } }ผลลัพธ์
Value Type 10 20 Reference Type 20 20