What is the StructLayoutAttribute effect for properties in C #?

I define the structures that should be received and sent over the communication channel between different devices and different programming languages. To do this, I explicitly define their layout in memory using StructLayoutAttribute (serialential, pack = 1 - in case it matters).

From the documentation, I know that it works when the structure contains only fields. It also works for β€œsimple” properties (with empty get, set;). However, I do not know if this is always the case.

So, my question about the effect of StructLayoutAttribute on properties is divided into two:

  • Do simple properties (again, empty get; set;) behave the same as fields?
  • How do other properties behave, for example, the properties that get them are calculated by other properties? Are they ignored (since I don't see the actual data item behind them)? Do they take up memory?
+5
source share
3 answers

Properties are not stored. StructLayoutAttribute does not affect them at all.

Auto-properties gain access to the generated support field, to which the StructLayoutAttribute obeys (since all fields obey this attribute). However, the order of these fields is not defined.

Since get properties that simply compute a value do not have storage, they are not marshaled.

+3
source

According to the documentation and my tests, FieldOffsetAttribute cannot be applied to properties. This leaves a question about LayoutKind.Sequential. According to this article , property fields appear at the end. Basically, do not use automatic properties if you care about the layout. Expand them and annotate the fields. The calculated properties are not displayed in the memory layout of the structure.

+2
source

Auto properties ( {get; set;} ) have an openly inaccessible support field, which is created automatically. In fact, if you use reflection to look at the fields of a class that has an auto property, you can see that there is a private field for this property. The code below prints <Bar>k__BackingField - a strange field name, but nonetheless a field name!

I can not say that I have tried the StructLayoutAttribute properties. If it works, it certainly just applies the same logic to the backup field.

 using System; using System.Reflection; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var fields = typeof(Foo).GetFields(BindingFlags.NonPublic | BindingFlags.Instance); Console.WriteLine(fields[0].Name); } } class Foo { public int Bar { get; set; } } } 
+1
source

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


All Articles