The size of the array of structures in bytes

I have an array of structures and I need to get its size in bytes

in c ++ i can do it with sizeof ()

but i need it c #

thnx

+6
source share
2 answers

Marshal.SizeOf(typeof(MyStruct)) * array.Length

+11
source

There is a sizeof operator. However, it can only be used in an unsafe context.

There is also a difference in the method proposed by Mehrdad, naming:

For all other types, including structures, the sizeof operator can only be used in insecure blocks of code. Although you can use the Marshal.SizeOf method, the value returned by this method does not always match the value returned by sizeof. Marshal.SizeOf returns the size after the type has been marshaled, while sizeof returns the size since it was allocated by the common language environment, including any addition.

a source

Example:

 unsafe { int size = sizeof(MyStruct)*myArray.Length; } 
+5
source

Source: https://habr.com/ru/post/885866/


All Articles