As far as I know how overloading works, it checks the number of parameters that you supply to it, and then checks which constructor it should use.
No, overloading is not based solely on the number of parameters - it is also based on their types.
However:
Since two of the constructors are the same, both take strings
This is problem. You cannot declare two constructors as follows:
public Foo(string x) { } public Foo(string y) { }
These signatures are facing overload.
I suggest having public static factory methods, so you can specify what you are trying to create:
public static Foo FromGears(string gears) { return new Foo(...); } public static Foo FromMaximumSpeed(string maxSpeed) { return new Foo(...); }
Then you can have one constructor that accepts both values, and a default value that is missing when calling the constructor from the factory method.
However, there are two other oddities in your description:
- You use strings for two values ββthat sound like they should be numbers (or maybe one number and one number and one)
- You talk about declaring constructors, but then use the word βmodifyβ as if they were going to modify an existing instance. This does not make sense - constructors are used to create new objects.
EDIT: Okay, now we know a little more, here is what I mean:
public class Car { private const int DefaultGears = 5; private const int DefaultTopSpeed = 180; private readonly int gears; private readonly int topSpeed; public Car(int gears, int topSpeed) { this.gears = gears; this.topSpeed = topSpeed; } public static Car CreateWithGears(int gears) { return new Car(gears, DefaultTopSpeed); } public static Car CreateWithTopSpeed(int topSpeed) { return new Car(topSpeed, DefaultGears); } }
Note that you can use optional parameters and named arguments for this too in C # 4:
public class Car { public const int DefaultGears = 5; public const int DefaultTopSpeed = 180; private readonly int gears; private readonly int topSpeed; public Car(int gears = DefaultGears, int topSpeed = DefaultTopSpeed) { this.gears = gears; this.topSpeed = topSpeed; } }
Then:
Car car = new Car(gears: 4); Car car = new Car(topSpeed: 30);
I would not recommend this at all, although, of course, you are not yet relatively new to this language. There are various subtleties around optional parameters.