Thursday, April 21, 2011

Can the get of a property be abstract and the set be virtual?

I have a base class like this:

public class Trajectory{
    public int Count { get; set; }
    public double Initial { get; set { Count = 1; } }
    public double Current { get; set { Count ++ ; } }
}

So, I have code in the base class, which makes the set-s virtual, but the get-s must stay abstract. So I need something like this:

...
public double Initial { abstract get; virtual set { Count = 1; } }
...

But this code gives an error. The whole point is to implement the counter functionality in the base class instead in all the derived classes. So, how can I make the get and set of a property with different modifiers?

From stackoverflow
  • split it into 2 functions:

    public double Initial
    {
        get { return GetInitial(); }
        set { SetInitial(value); }
    }
    
    protected virtual void SetInitial(double value)
    {
        Count = 1;
    }
    
    protected abstract double GetInitial();
    
  • Make it neither abstract nor virtual. And make the backing field private. That way, a derived class cannot override it nor can it mess with it.

  • No, you can't. At least I haven't found a solution.

    If property is marked as abstract then neither it's getter and setter can have bodies.

0 comments:

Post a Comment