Επεξεργασία

Κοινή χρήση μέσω


sizeof operator - determine the memory needs for a given type

The sizeof operator returns the number of bytes occupied by a variable of a given type. The argument to the sizeof operator must be the name of an unmanaged type or a type parameter that is constrained to be an unmanaged type.

The sizeof operator requires an unsafe context. However, the expressions presented in the following table are evaluated in compile time to the corresponding constant values and don't require an unsafe context:

Expression Constant value
sizeof(sbyte) 1
sizeof(byte) 1
sizeof(short) 2
sizeof(ushort) 2
sizeof(int) 4
sizeof(uint) 4
sizeof(long) 8
sizeof(ulong) 8
sizeof(char) 2
sizeof(float) 4
sizeof(double) 8
sizeof(decimal) 16
sizeof(bool) 1

You also don't need to use an unsafe context when the operand of the sizeof operator is the name of an enum type.

The following example demonstrates the usage of the sizeof operator:

public struct Point
{
    public Point(byte tag, double x, double y) => (Tag, X, Y) = (tag, x, y);

    public byte Tag { get; }
    public double X { get; }
    public double Y { get; }
}

public class SizeOfOperator
{
    public static void Main()
    {
        Console.WriteLine(sizeof(byte));  // output: 1
        Console.WriteLine(sizeof(double));  // output: 8

        DisplaySizeOf<Point>();  // output: Size of Point is 24
        DisplaySizeOf<decimal>();  // output: Size of System.Decimal is 16

        unsafe
        {
            Console.WriteLine(sizeof(Point*));  // output: 8
        }
    }

    static unsafe void DisplaySizeOf<T>() where T : unmanaged
    {
        Console.WriteLine($"Size of {typeof(T)} is {sizeof(T)}");
    }
}

The sizeof operator returns a number of bytes that would be allocated by the common language runtime in managed memory. For struct types, that value includes any padding, as the preceding example demonstrates. The result of the sizeof operator might differ from the result of the Marshal.SizeOf method, which returns the size of a type in unmanaged memory.

C# language specification

For more information, see The sizeof operator section of the C# language specification.

See also