Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StructLayout only for struct?

Tags:

c#

I noticed that there are many places we have something like this:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
    public class E2H_LANEFIND_DATA_T
    {
....
}

class definition with StructLayout. Is that ok or StructLayout is only for struct?

like image 388
5YrsLaterDBA Avatar asked Jul 28 '10 16:07

5YrsLaterDBA


1 Answers

The documentation clearly states:

You can apply this attribute to classes or structures.

Typically, the common language runtime controls the physical layout of the data fields of a class or structure in managed memory. However, if you want to arrange the class or structure needs in a certain way, you can use StructLayoutAttribute. Explicit control of a class layout is important if the class is to be passed to unmanaged code that expects a specific layout.

Emphasis was mine.

The main consideration to make in this situation is whether you want your instances to be passed by value or by reference, in which case you would respectively use a struct or a class.

like image 139
Mark Rushakoff Avatar answered Sep 19 '22 01:09

Mark Rushakoff