Struct - Layout.Explicit - Constructor - fully assign fields
Asked Answered
H

3

10

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?

Hollis answered 7/2, 2012 at 10:41 Comment(0)
V
10

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"
Vienne answered 16/11, 2015 at 1:1 Comment(1)
This is very useful. Doing this speeds up the code by one or more nanoseconds (depending on how many fields are).Pulsar
M
0

Seems like it is not possible, and the discussion about it has been closed down:

Here is a link to the discussion regarding this issue:

https://github.com/dotnet/roslyn/issues/7323

Mariselamarish answered 17/6, 2017 at 16:58 Comment(0)
M
-2

You need to initialize all of the fields of a struct if you define a custom constructor. See this MSDN tutorial in structs for more information - specifically under the Constructors and Inheritence heading.

Here is an paragraph extracted from that link with regards to this:

Structs can declare constructors, but they must take parameters. It is an error to declare a default (parameterless) constructor for a struct. Struct members cannot have initializers. A default constructor is always provided to initialize the struct members to their default values.

Monty answered 7/2, 2012 at 10:46 Comment(3)
I'm talking about something else.Hollis
@zgnilec In that case I would suggest reviewing your question as it doesn't make a lot of sense.Monty
Well, maybe someone else will understand me.Hollis

© 2022 - 2024 — McMap. All rights reserved.