Struct pointer (address), and default constructor

  • A+
Category:Languages

Does taking address of a C# struct cause default constructor call?

For example, I got such structs:

[StructLayout(LayoutKind.Sequential, Pack = 1)] public struct HEADER {     public byte OPCODE;     public byte LENGTH; }  [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct S {     public HEADER Header;     public int Value; } 

Then, of course, I can't do this:

S s;                // no constructor call, so... var v = s.Value;    // compiler error: use of possibly unassigned field 'Value' 

But once I obtain pointer to the struct, I can read its fields even without using the pointer, and even embedded struct's fields:

S s; S* ps = &s; var v1 = ps->Value;        // OK, expected var v2 = s.Value;          // OK! var len = s.Header.LENGTH; // OK! 

So, does it call the default constructor somehow, or - once I take the address - C# stops caring about the memory?

PS: The memory seems to be zero-initialized anyway.

 


Does taking address of a C# struct cause default constructor call?

No. It just circumvents the compiler check.

The "use of possibly unassigned field" is a nicety to protect you against yourself. But it can easily be worked around. And in this case it does not seem so critical.

PS: The memory seems to be zero-initialized anyway.

Yes, that will almost always (see below) be the case in .NET, making the "default constructor call" question a bit academic. What happens to your memory is not so tightly coupled to the compiler warning.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: