Suppose for instance I’m defining a Complex class for representing complex numbers. I would like to define two constructors, so that I can write for example:
Complex z1 = new Complex(x: 4, y: 3);
Complex z2 = new Complex(r: 2, theta: Math.PI / 4);
However, I cannot define the constructors like this:
public Complex(double x, double y) { ... }
public Complex(double r, double theta) { ... }
because both constructors would have the same signature, which is not allowed. But in C# 4 I can write this, using an optional argument:
public Complex(double x, double y) { ... }
public Complex(double r, double theta, bool unused=true) { ... }
It works, I can then use the above constructor calls as intended. The sole purpose of the unused argument is to make the signatures different; it’s totally unused, both when defining and when calling the constructor.
To me this seems to be a an ugly trick: is there any better option?
Make the constructor private and have a static factory style function.
You can do validation on the inputs based on what they should be.
Another possibility would be to create a type that encapsulates the inputs and use constructors as you previously mentioned.