I often see StackOverflow answers that confuse the
sizeof operator with the
Marshal.SizeOf method. These two operators do different things and can return different results, so it is important to know which is which.
In a nutshell, the difference is: the
sizeof operator takes a type name and tells you how many bytes of managed memory need to be allocated for an instance of that struct.[1. I don't have to tell long-time readers of this blog that of course this is not necessarily stack memory; structs are allocated off the heap when they are array elements, fields of a class, and so on.] By contrast,
Marshal.SizeOf takes either a type object or an instance of the type, and tells you how many bytes of unmanaged memory need to be allocated. These can be different for a variety of reasons. The name of the type gives you a clue:
Marshal.SizeOf is intended to be used when marshaling a structure to unmanaged memory.
Another difference between the two is that the
sizeof operator can only take the name of an unmanaged type; that is, a struct type whose fields are only integral types, Booleans, pointers and so on. (See the specification for an exact definition.)
Marshal.SizeOf by contrast can take any class or struct type.