Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof() operator for types

Tags:

c#

.net

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?

like image 668
c00000fd Avatar asked Aug 04 '13 01:08

c00000fd


1 Answers

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

like image 67
hazzik Avatar answered Oct 01 '22 13:10

hazzik