When you're dealing with structs, C# wants to make sure that you've initialized all of the struct's fields.
One option is to provide a constructor that will call the default constructor first, then do your custom initialization later:
public S(int x) : this()
{
/* custom initialization logic */
}
Another option is to provide a constructor that provably initializes all fields of the struct in its own body, in which case you don't need to chain the default constructor:
public S(int x)
{
this.X = x;
/* custom initialization logic */
}
Another option is to skip calling a constructor, and instead initialize the struct manually, just before you actually use it:
S s;
s.X = 5;
Out of the above options, only the first performs a logical call to the default constructor, while the other two skip the call.
The bad news is that, behind the scenes, the CLR will always give you zero-initialized memory for safety reasons, which is pretty much exactly equivalent to calling the C# default constructor. You can observe it like this:
S s;
S* ptr = &s;
int x = (*ptr).X;
Console.WriteLine(x); // will print 0
The good news is that, for most cases, this doesn't matter. The C# default constructors aren't really constructors in the CLR sense. The expression new T()
for any T : struct
is equivalent to default(T)
, which is simply a way to express getting a zero-initialized instance of a struct of type T
. It's also why you can't make it private or add custom logic to it.
Therefore, C# default struct constructors cannot have any logical externally observable side-effects. Which brings us to a question: what kinds of effects are you trying to avoid?
Keep in mind that if your problem is that your struct is invalid for the all-zero bit pattern and you're afraid that some client code might attempt to use it like that, there is a workaround:
struct S
{
private bool _isValid;
/* rest of your struct */
}
Any zero-initialized struct will have its validity flag not set, and you can use that to throw exceptions as soon as any operation (that you can control) is performed on your struct.
After all this, if for any reason you still need to a struct instance that has somehow skipped calling any constructor (whether a real or an apparent one), you'll have to allocate some memory for the struct yourself:
S* ptr = (S*) Marshal.AllocHGlobal(Marshal.SizeOf<S>());
You can now use expressions of the form (*ptr).X
or ptr->X
to read and write to that struct directly.