Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract property without setter

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.

like image 637
Kite Avatar asked Jan 22 '26 10:01

Kite


1 Answers

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?

like image 171
Dmitry Bychenko Avatar answered Jan 24 '26 01:01

Dmitry Bychenko