Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct constructor calls this()

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?

like image 521
flakes Avatar asked Mar 16 '15 04:03

flakes


1 Answers

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.

like image 161
Jonathon Reinhart Avatar answered Oct 11 '22 10:10

Jonathon Reinhart