How to get the sizeof a datatype in C#?


In C#, the sizeof operator returns a number of bytes that would be allocated by the common language runtime in managed memory.

For example, the following returns the sizeof an integer type.

Example: Convert string to int using Parse()
sizeof(int); //returns 4
sizeof(char); // returns 2
sizeof(bool);//returns 1
sizeof(long);  //returns 8
sizeof(float); //returns 4
sizeof(double);//returns 8 
sizeof(decimal);//returns 16

It can be used with the enum type, as shown below:

Example: sizeof with Enum
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; }
}

Sizeof(Point); // returns 24

however, the sizeof operator cannot determine the size of a variable.

Example: Invalid sizeof Usage
int i = 10;
sizeof(i);// compilation error: 'i' does not have a predefined size, therefore sizeof can only be used in an unsafe context
sizeof(string);//compilation error: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')