Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct pointer (address), and default constructor

Tags:

c#

c#-7.3

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.

like image 276
lisz Avatar asked Feb 08 '19 09:02

lisz


People also ask

Can a struct have a default constructor?

Implicitly-declared default constructor If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

Does struct have default constructor C#?

C# does not allow a struct to declare a default, no-parameters, constructor. The reason for this constraint is to do with the fact that, unlike in C++, a C# struct is associated with value-type semantic and a value-type is not required to have a constructor.

Does a struct have a constructor?

struct can include constructors, constants, fields, methods, properties, indexers, operators, events & nested types. struct cannot include a parameterless constructor or a destructor. struct can implement interfaces, same as class. struct cannot inherit another structure or class, and it cannot be the base of a class.

Can we make constructor in struct in C?

Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation.


1 Answers

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.

like image 168
Henk Holterman Avatar answered Oct 02 '22 19:10

Henk Holterman