Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract Classes and ReadOnly Properties

Tags:

c#

.net

oop

vb.net

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.

like image 279
serhio Avatar asked Jan 12 '11 18:01

serhio


People also ask

Can abstract classes have properties?

An abstract class not only contains abstract methods and assessors but also contains non-abstract methods, properties, and indexers.

Can an abstract class have private properties?

Yes, you can have a private field within an abstract class. This field will only be accessible to functions within that abstract class though. Any classes which inherit from your abstract class will not be able to access the field.

What are the properties of read-only?

A class property declared read-only is only allowed to be initialized once, and further changes to the property is not allowed. Read-only class properties are declared with the readonly keyword* in a typed property.


2 Answers

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.

like image 85
Marc Gravell Avatar answered Oct 06 '22 23:10

Marc Gravell


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; }
}
like image 30
Timwi Avatar answered Oct 06 '22 21:10

Timwi