Compartir a través de


sizeof (C# Reference) 

Used to obtain the size in bytes for a value type. For example, the size of the int type can be retrieved like this:

int intSize = sizeof(int);

Remarks

The sizeof operator can be applied only to value types, not reference types.

Note

From version 2.0 of C# onwards, applying sizeof to predefined types no longer requires that unsafe mode be used.

The sizeof operator may not be overloaded. The values returned by the sizeof operator are of the type int. The following table shows the constant values that represent the sizes of certain predefined types.

Expression

Result

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(bool)

1

For all other types, including structs, the sizeof operator can only be used in unsafe code blocks. Although you can use the 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

// cs_operator_sizeof.cs
// compile with: /unsafe
using System;
class MainClass
{
    unsafe 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 following sections in the C# Language Specification:

  • 18.5.8 The sizeof operator

See Also

Reference

C# Keywords
Operator Keywords (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference