Shoud Do I use LayoutKind.Auto for my structures if they are not running in COM Interop?

By default, structs in C # are implemented using [StructLayout( LayoutKind.Sequential )]for reasons basically stating that these types of objects are commonly used for COM Interop, and their fields should remain in the order in which they were defined. Classes have LayoutKind.Auto.

My question is, should I explicitly indicate my structures as [StructLayout( LayoutKind.Auto )]this will give me any default benefits? I mean, if structs are initialized on the stack , will it have any value, i.e. GC do not need to move them? It will also help when structures are initialized on the heap - i.e. Are part of some class?

+3
source share
2 answers

The only possible advantage that I can think of is your structure, which takes up less memory. But if you have such a large structure, first of all you should possibly reorganize it into a class.

The potential problem is that you want Marshall structto byte[]use Marshal.PtrToStructure, how can you guarantee that the byte order will be what you expect?

, , , ... , , , , , , .

+2

, , . .

, , CLR , , , ( , , ). , (, KeyValuePair), .

+1

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


All Articles