As far as I know the way overloading works is that it checks the amount of parameters you supply it with and then checks which constuctor it has to use.
No, overloading isn't based solely on the number of parameters - it's based on their types too.
However:
As two of the constructors are the same, both accepts strings
That's a problem. You can't declare two constructors like this:
public Foo(string x)
{
}
public Foo(string y)
{
}
Those signatures clash as far as overloading is concerned.
I would suggest having public static factory methods, so you can specify what you're trying to create:
public static Foo FromGears(string gears)
{
return new Foo(...);
}
public static Foo FromMaximumSpeed(string maxSpeed)
{
return new Foo(...);
}
You'd then possibly have one constructor which accepted both values, and default whichever one's missing when you call the constructor from the factory method.
However, there are two other oddities in your description:
- You're using strings for two values which sound like they should be numbers (or possibly one number, and one number-and-unit)
- You're talking about declaring constructors, but then using the word "change" as if they're going to change an existing instance. That doesn't make sense - constructors are used to create new objects.
EDIT: Okay, now we know a bit more, here's the sort of thing 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 could 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 wouldn't recommend that in general though - certainly not while you're still relatively new to the language. There are various subtleties around optional parameters.