sizeof (C# Reference)

Used to obtain the size in bytes for an unmanaged type.

Unmanaged types include:

  • The simple types that are listed in the following table:
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 (Unicode)
sizeof(float) 4
sizeof(double) 8
sizeof(decimal) 16
sizeof(bool) 1
  • Enum types.

  • Pointer types.

  • User-defined structs that do not contain any instance fields or auto-implemented instance properties that are reference types or constructed types.

The following example shows how to retrieve the size of an int:

// Constant value 4:  
int intSize = sizeof(int);   

Remarks

Starting with version 2.0 of C#, applying sizeof to simple or enum types no longer requires that code be compiled in an unsafe context.

The sizeof operator cannot be overloaded. The values returned by the sizeof operator are of type int. The previous table shows the constant values that are substituted for sizeof expressions that have certain simple types as operands.

For all other types, including structs, the sizeof operator can be used only in unsafe code blocks. Although you can use the Marshal.SizeOf method, the value returned by this method is not always the same as the value returned by sizeof. Marshal.SizeOf returns the size after the type has been marshaled, whereas sizeof returns the size as it has been allocated by the common language runtime, including any padding.

Example

class MainClass
{
    // unsafe not required for primitive types
    static void Main()
    {
        Console.WriteLine("The size of short is {0}.", sizeof(short));
        Console.WriteLine("The size of int is {0}.", sizeof(int));
        Console.WriteLine("The size of long is {0}.", sizeof(long));
    }
}
/*
Output:
    The size of short is 2.
    The size of int is 4.
    The size of long is 8.
*/

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also