serhio
serhio

Reputation: 28586

Abstract Classes and ReadOnly Properties

Let's have three classes;

Line
PoliLine
SuperPoliLine

for all that three classes a Distance is defined.

But only for the Line a Distance can be Set.

Is there a possibility to build a common abstract (MustInherit) class Segment, having a Distance as (abstract +? ReadOnly) member?

Question for VB.NET, but C# answers welcomed too.


Business Background

Imagine a Bus. It has a lot of Stations, MainStations, and 2 TerminalStations. So Line is between 2 Stations, PoliLine is between 2 MainStations, and SuperPoliLine is between 2 TerminalStations. All "lines" are "Segments", but only the distance A->B between 2 stations - Line can be defined.

Upvotes: 7

Views: 2611

Answers (3)

Pedro
Pedro

Reputation: 382

public class Segment
{
    private int distance;
    public virtual int Distance
    {
        get { return distance; }
        set { distance = value; }
    }
}

public class Line : Segment
{
    public override int Distance
    {
        get { return base.Distance; }
        set
        {
            // do nothing
        }
    }
}

EDITED VERSION:

    public abstract class Segment
    {            
        public abstract int Distance { get; set; }
    }

    public class Line : Segment
    {
        private int distance;
        public override int Distance
        {
            get { return distance; }
            set
            {
                // do nothing
            }
        }
    }

Upvotes: 1

Timwi
Timwi

Reputation: 66583

Since you want it settable in one class but unsettable in the others, I would customarily not use a property for the one that is “special” (the setter in this case).

public class Segment
{
    protected int _distance;
    public int Distance { get { return _distance; } }
}

public class Line : Segment
{
    public int SetDistance(int distance) { _distance = distance; }
}

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063005

You can't override and re-declare (to add the set) at the same time - but you can do:

Base class:

protected virtual int FooImpl { get; set; } // or abstract
public int Foo { get { return FooImpl; } }

Derived class:

new public int Foo {
    get { return FooImpl; }
    set { FooImpl = value; }
}

// your implementation here... 
protected override FooImpl { get { ... } set { ... } }

Now you can also override FooImpl as needed.

Upvotes: 1

Related Questions