First of all, a small disclaimer before the actual question:
I know there are a lot of closed/duplicate questions regarding the difference between the
sizeofoperator and theMarshal.SizeOf<T>method, and I do understand the difference between the two. Here I'm talking about theSizeOf<T>method in the newUnsafeclass
So, I'm not sure I understand the actual difference between these two operations, and whether there's a specific difference when using the method on a struct/class in particular.
The sizeof operator takes a Type name and returns the number of managed bytes it is supposed to take up when allocated (ie. an Int32 will return 4, for example).
The Unsafe.SizeOf<T> method on the other hand, is implemented in IL like all the other methods in the Unsafe class, and looking at the code here's what it does:
.method public hidebysig static int32 SizeOf<T>() cil managed aggressiveinlining
{
.custom instance void System.Runtime.Versioning.NonVersionableAttribute::.ctor() = ( 01 00 00 00 )
.maxstack 1
sizeof !!T
ret
}
Now, if I'm not wrong, the code is just calling sizeof !!T which is the same as sizeof(T) (calling the sizeof operator with the type name T), so wouldn't the two of them be exactly equivalent?
Also, I see the method is also allocating a useless object (the NonVersionableAttribute) in the first line, so wouldn't that cause a small amount of memory to be heap-allocated as well?
My question is:
Is it safe to say that the two methods are perfectly equivalent and that therefore it is just better to use the classic
sizeofoperator, as that also avoid the allocation of that attribute in theSizeOf<T>method? Was thisSizeOf<T>method added to theUnsafeclass just for convenience at this point?