Why can’t I use sizeof() on simple structs?
eg:
private struct FloatShortPair
{
public float myFloat;
public short myShort;
};
int size = sizeof(FloatShortPair); //CS0233
error CS0233: ‘FloatShortPair’ does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
MSDN states:
The sizeof operator can only be used for types that are compile-time
constants. If you are getting this error, make sure that the size of
the identifier can be determined at compile time. If it cannot, then
use SizeOf instead of sizeof.
How are float and short not compile time constants? 8-/
The sizes of
shortandfloatare constant – but how the CLR decided to pack that float in memory isn’t necessarily constant. For example, on a 64-bit processor it may decide to align each value on an 8-byte boundary.From the C# 4 spec, section 18.5.8:
Note that you can use
sizeofin this situation, within anunsafecontext. Whether you should use that orMarshal.SizeOfdepends on what you’re trying to do.