Reputation: 79
using the C# feature of the contructor recalling is convenient but in this case it compromises the final result.
class Car{
protected static int numCar;
public string Owner{get; private set;}
static Car() { // CRL will set it at the first Car object allocation
Car.numAuto = 0;
}
public Car():this("No One") {
Car.numCar ++;
}
public Car(string owner)
{
Car.numCar ++;
this.Owner=owner;
}
...
//other methods
...
}
Then, inside the Main(), I declare and allocate my first Car object using the default constructor... this operation increments twice the static Car.numCar member:
Car c= new Car();
Console.Write(car.numCar), // 2
My question is: how to keep both constructors and avoid this behaviour? My goal is to keep them all but using the last instruction obtain on my console the value '1'. Thank you
Upvotes: 0
Views: 201
Reputation: 15055
Just take Car.numCar++
out of your second constructor. It will always call the 3rd one giving you the result you want.
Upvotes: 2