C#C
C#17mo ago
hadeedji

✅ Positional record with alternate constructor

Say we have this record:
public record Point(float x, float y);


And we wanna provide a way for it to be initialized from doubles too:
public record Point(float x, float y) {
    public Point(double x, double y) {
        this.x = (float) x;
        this.y = (float) y;
    }
}


But the compiler complains "A constructor declared in 'record' with parameter list must have 'this' constructor"
It wants me to do something like this:
public record Point(float x, float y) {
    public Point(double x, double y) : this(0, 0) { // The numbers here can be anything
        this.x = (float) x;
        this.y = (float) y;
    }
}


This doesn't feel right to me, seems like I'm going against the language and doesn't look like idiomatic C#. Because we're setting the fields then setting them again. But I don't see why this can't work, it should be possible to specify a constructor with some other parameters than the primary constructor, assuming all the fields get initialized. I'm looking for ways to achieve this result with idiomatic C# that isn't a lot of code, like removing the positional parameters and writing those properties manually. Thank you.
Was this page helpful?