Reputation: 22327
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
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
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
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
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
Reputation: 727067
You can use the Marshal.SizeOf()
method, or use sizeof
in unmanaged code:
Console.WriteLine(Marshal.SizeOf(typeof(int)));
Here is a link to Eric Lippert's blog describing the difference between the two sizeof options.
Upvotes: 5