Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Dùng toán tử sizeof() để tìm kích thước kiểu dữ liệu hoặc biến trong C#

Toán tử sizeof() trả về kích thước (số byte) của một kiểu dữ liệu giá trị (value type).

Cú pháp:

sizeof(int);    // 4 byte
sizeof(double); // 8 byte

Ví dụ: Kích thước các kiểu cơ bản

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The size of int is {0}", sizeof(int));
            Console.WriteLine("The size of char is {0}", sizeof(char));
            Console.WriteLine("The size of short is {0}", sizeof(short));
            Console.WriteLine("The size of long is {0}", sizeof(long));
            Console.WriteLine("The size of double is {0}", sizeof(double));
            Console.ReadLine();
        }
    }
}

Kết quả

The size of int is 4
The size of char is 2
The size of short is 2
The size of long is 8
The size of double is 8

Lưu ý: sizeof() chỉ dùng được với value types (các kiểu gốc, struct, enum). Không dùng cho reference types (class, string, array). Cần bật unsafe context cho một số trường hợp đặc biệt.