შენიშვნა
ამ გვერდზე წვდომა მოითხოვს ავტორიზაციას. შეგიძლიათ სცადოთ შესვლა ან შეცვალოთ დირექტორიები.
ამ გვერდზე წვდომა მოითხოვს ავტორიზაციას. შეგიძლიათ სცადოთ დირექტორიების შეცვლა.
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 a built-in unmanaged type.
The expressions presented in the following table are evaluated at 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 |
The size of a built-in, unmanaged type is a compile-time constant.
In unsafe code, you can use sizeof as follows:
- A type parameter that is constrained to be an unmanaged type returns the size of that unmanaged type at runtime.
- A managed type or a pointer type returns the size of the reference or pointer, not the size of the object it refers to.
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.
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.