Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct - Layout.Explicit - Constructor - fully assign fields

Tags:

c#

struct

Why if i use:

struct MyStruct
{
        [FieldOffset (0)] public uint Data;
        [FieldOffset (0)] public byte Something;
}

public MyStruct (uint pData)
{
   Data = pData; // setting Data field also sets Something field
}

C# says i need to assign 'Something' field :/ I know I can do a "Constructor : this ()" but compiler should know 'Data' field contains 'Something' field.

So, I should call parameterless constructor first, is it the only way?

like image 302
apocalypse Avatar asked Feb 07 '12 10:02

apocalypse


1 Answers

Yes, you'll need to call the default constructor.

public MyStruct (uint pData) : this()
{
   //...
}

The compiler will then generate the following IL instructions at the beginning of your constructor:

ldarg.0           // Push address of struct onto stack
initobj MyStruct  // Pop address of struct and initialize it with "all zeros"
like image 194
Mårten Wikström Avatar answered Sep 24 '22 05:09

Mårten Wikström