Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

properties

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?

like image 221
K. Georgiev Avatar asked Jun 06 '10 19:06

K. Georgiev


People also ask

Can abstract methods be virtual?

Yes, abstract methods are virtual by definition; they must be overridable in order to actually be overridden by subclasses: When an instance method declaration includes an abstract modifier, that method is said to be an abstract method.

What is the difference between virtual and abstract properties?

Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method. So, abstract methods have no actual code in them, and (non-abstract) subclasses HAVE TO override the method.

Can properties be abstract?

An abstract property declaration does not provide an implementation of the property accessors -- it declares that the class supports properties, but leaves the accessor implementation to derived classes. The following example demonstrates how to implement the abstract properties inherited from a base class.

Can an abstract class have fields C#?

C# Abstract Class FeaturesAn Abstract class can have constants and fields.


1 Answers

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();
like image 169
max Avatar answered Oct 01 '22 02:10

max