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. In safe code, 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. Unmanaged types include all numeric types, enum types, and tuple and struct types where all members are unmanaged types.
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 |
In unsafe code, the argument to sizeof
can include pointer types and managed types, including unconstrained type parameters. Examples include object
and string
.
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 the number of bytes 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.
In unsafe code, when the argument is a managed type, the sizeof
operator returns the size of a reference, not the number of bytes allocated for an instance of that type.
Important
The value returned by sizeof
can differ from the result of Marshal.SizeOf(Object), which returns the size of the type in unmanaged memory.
C# language specification
For more information, see The sizeof operator section of the C# language specification.