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.
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.
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.
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.
Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With