BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Sizeof Keyword

In some situations it is necessary to know the size of a value type, such as a built-in numeric data type or a custom structure. The number in bytes can be looked up or calculated, or the sizeof keyword can be used to automatically obtain the size.

Sizeof

Although quite uncommon, sometimes you will wish to obtain the size of a value type in bytes. For example, you may need to know the size when passing values to unmanaged code or when allocating memory or stack space. When such a situation occurs, you can determine the size using the sizeof keyword. The type that you are examining may be a standard value type, such as the numeric data types, or one of your own custom structures. However, it may not be a reference type or a structure with fields or properties that hold reference types.

The sizeof keyword requires that you pass the type as a parameter. The result is an integer containing the number of bytes required to hold a value of the type. For example, the following code displays the size of an integer, which is four bytes.

Console.WriteLine(sizeof(int)); // 4

Obtaining the Size of Custom Types

When determining the size of a structure, the syntax is the same but the sizeof call must be placed within an unsafe code block. To demonstrate, we can use the following structure, which represents a three-dimensional vector.

struct Vector3D
{
    int X { get; set; }
    int Y { get; set; }
    int Z { get; set; }

    double Length
    {
        get
        {
            return Math.Sqrt(X * X + Y * Y + Z * Z);
        }
    }
}

To obtain the size of a Vector3D instance, we can use the following code. To run this code, ensure that you compile it with the option to permit unsafe code.

unsafe { Console.WriteLine(sizeof(Vector3D)); }   // 12

NB: When using the .NET framework 1.1, all calls to sizeof must reside in an unsafe code block.

2 October 2011