ภาพรวม
ใน C# ใช้ sizeof ได้เฉพาะใน unsafe context สำหรับ primitive types วิธีปลอดภัยคือใช้ BitConverter.GetBytes แปลงค่าเป็น byte array แล้ววัด Length
โค้ดตัวอย่าง
using System;
class Demo {
public static void Main() {
int x = 42;
// ใช้ sizeof (ต้องเป็น unsafe context สำหรับบาง type)
unsafe {
int size1 = sizeof(int);
Console.WriteLine($"sizeof(int) = {size1}");
}
// ไม่ใช้ sizeof - ใช้ BitConverter
byte[] bytes = BitConverter.GetBytes(x);
int size2 = bytes.Length;
Console.WriteLine($"BitConverter.GetBytes(int).Length = {size2}");
// ทดสอบกับ type อื่นๆ
TestSize(123L); // long
TestSize(3.14f); // float
TestSize(3.14); // double
TestSize(true); // bool
TestSize('A'); // char
TestSize("hello"); // string (reference)
}
static void TestSize<T>(T value) where T : struct {
byte[] bytes = BitConverter.GetBytes(value);
Console.WriteLine($"sizeof({typeof(T).Name}) = {bytes.Length} bytes");
}
}
ผลลัพธ์
sizeof(int) = 4
BitConverter.GetBytes(int).Length = 4
sizeof(long) = 8 bytes
sizeof(float) = 4 bytes
sizeof(double) = 8 bytes
sizeof(bool) = 1 bytes
sizeof(char) = 2 bytes
ขนาดของ Primitive Types ใน C#
| Type | Size (bytes) | Range |
|---|---|---|
| bool | 1 | true/false |
| byte / sbyte | 1 | 0-255 / -128 to 127 |
| short / ushort | 2 | -32,768 to 32,767 / 0-65,535 |
| int / uint | 4 | ±2.14B / 0-4.29B |
| long / ulong | 8 | ±9.22E18 / 0-1.84E19 |
| float | 4 | ~±1.5e−45 to ±3.4e38 |
| double | 8 | ~±5.0e−324 to ±1.7e308 |
| decimal | 16 | ±1.0e−28 to ±7.9e28 |
| char | 2 | UTF-16 code unit |
หมายเหตุสำคัญ
BitConverter.GetBytesทำงานได้กับ value types (struct) เท่านั้น- สำหรับ reference types (class, string, array) จะได้ขนาดของ reference (4 หรือ 8 bytes ขึ้นอยู่กับ platform)
Marshal.SizeOf<T>()ใช้สำหรับ interop/unmanaged memory layout- ใน unsafe context:
sizeof(MyStruct)ใช้ได้กับ struct ที่ไม่มี reference fields