c00000fd
c00000fd

Reputation: 22327

sizeof() operator for types

I would normally do this in my C++ code:

int variable = 10;
int sizeOfVariable = sizeof(variable);   //Returns 4 for 32-bit process

But that doesn't seem to work for C#. Is there an analog?

Upvotes: 15

Views: 37204

Answers (5)

moien
moien

Reputation: 1079

You can use sizeof on user-defined structs in unsafe contexts but unlike Marshal.SizeOf it does not support boxed objects

Upvotes: 1

xanatos
xanatos

Reputation: 111940

There are only a few standard situations where you'll want to do it:

int x = sizeof(T) // where T is a generic type

sadly it doesn't work :-)

int x = Marshal.SizeOf(T) // where T is a generic type

it does work except for char and bool (Marshal.SizeOf(typeof(char)) == 1 instead of 2, Marshal.SizeOf(typeof(bool)) == 4 instead of 1)

int x = sizeof(IntPtr);

it doesn't work, but you can do it as

int x = Marshal.SizeOf(typeof(IntPtr));

or, better

int x = IntPtr.Size;

All the other basic types (byte, sbyte, short, ushort, int, uint, long, ulong, float, double, decimal, bool, char) have a fixed length, so you can do sizeof(int) and it will always be 4.

Upvotes: 7

hazzik
hazzik

Reputation: 13374

The sizeof operator in C# works only on compile-time known types, not on variables (instances).

The correct example would be

int variable = 10;
int sizeOfVariable = sizeof(int);

So probably you are looking for Marshal.SizeOf which can be used on any object instances or runtime types.

int variable = 10;
int sizeOfVariable = Marshal.SizeOf(variable);    

See here for more information

Upvotes: 32

Mitch Wheat
Mitch Wheat

Reputation: 300797

.NET 4.0 onwards:

if (Environment.Is64BitProcess)
    Console.WriteLine("64-bit process");
else
    Console.WriteLine("32-bit process");

Older versions of .NET framework:

public static bool Is64BitProcess
{
    get { return IntPtr.Size == 8; }
}

(From your example I'm assuming you want to do this to determine the bitness of the process, which may in fact not be what you are trying to do!)

Upvotes: 10

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

You can use the Marshal.SizeOf() method, or use sizeof in unmanaged code:

Console.WriteLine(Marshal.SizeOf(typeof(int)));

This prints 4 on ideone.

Here is a link to Eric Lippert's blog describing the difference between the two sizeof options.

Upvotes: 5

Related Questions