C# 2.0: sizeof(MyStruct) ?
I'm trying C# 2.0 beta 2.
The online help says sizeof operator accept a value type parameter,
but the struct is a value type, too. Why compiler complains the code:
int i = sizeof(MyStruct);
I know I can use unsafe code and Marshal.SizeOf() to get
the size of a structure. I'm just wondering how I can use
sizeof operator to do the same thing.
Thanks!
[376 byte] By [
huanlin] at [2007-12-16]
You shouldn't need to use Marshal.SizeOf but you do need to wrap the sizeof keyword in an unsafe context if you're not using it on the built-in value types (§27.5.8 in the current ECMA standard revision).
So you must either add the unsafe modifier to the method declaration, or use an inline unsafe block, like so:
int i;
unsafe { i = sizeof(MyStruct); }
// can use the value of i here...
Some additional info from the C# reference documentation:
For all other [non built-in] types, including structs, the sizeof operator can only be used in unsafe code blocks. Although you can use the Marshal.SizeOf method, the value returned by this method is not always the same as the value returned by sizeof. Marshal.SizeOf returns the size after the type has been marshaled whereas sizeof returns the size as it has been allocated by the Common Language Runtime, including any padding.
Michael Blome
Visual C# Documentation Manager