I am writing some code, and I found that when I create a new abstract property without setter, I can't set its value in the constructor. Why is this possible when we are using a normal property? What's the difference?
protected Motorcycle(int horsePower, double cubicCentimeters)
{
this.HorsePower = horsePower; //cannot be assigned to -- it is read only
this.CubicCentimeters = cubicCentimeters;
}
public abstract int HorsePower { get; }
public double CubicCentimeters { get; }
It's obvious that if we want to set it in the constructor, we should use protected or public setter.
Yes you have compile time error since there's no guarantee, that HorsePower has a backing field to assign to. Imagine,
public class CounterExample : Motorcycle {
// What "set" should do in this case?
public override int HorsePower {
get {
return 1234;
}
}
public CounterExample()
: base(10, 20) {}
}
What should this.HorsePower = horsePower; do in this case?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With