I came across the following code snippet and was wondering what the purpose of writing a constructor this way was?
public struct DataPoint{
public readonly long X;
public readonly double Y;
public DataPoint(long x, double y) : this() {
this.X = x;
this.Y = y;
}
}
Doesn't this()
just set X
and Y
to zero? Is this not a pointless action seeing as afterwards they are immediately set to x
and y
?
public DataPoint(long x, double y) : this() {
This calls the default constructor for the struct
, which is automatically provided by the compiler, and will initialize all fields to their default values.
In this case, your custom constructor is assigning all fields anyway, so there's no point. But let's say you only assigned X
, and didn't call the default constructor:
public struct DataPoint{
public readonly long X;
public readonly double Y;
public DataPoint(long x) {
this.X = x;
}
}
This would generate a compiler error, because Y
is not assigned in your parameterized constructor, and because you've defined it, the default constructor is not publicly visible to consumers.
Adding this()
to the initialization list ensures that all fields are initialized, even if you aren't the one to do so.
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