Reputation: 41
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.
Upvotes: 3
Views: 141
Reputation: 317
The abstract keyword in c# specifies classes or members that the implementation must be provided by the derived class.
Upvotes: 0
Reputation: 186678
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?
Upvotes: 8