A readonly field should be used when you have a variable that will be known at object-instatiation which should not be changed afterwards.
However one is not allowed to assign readonly fields from constructors of subclasses.
This doesn’t even work if the superclass is abstract.
Does anyone have a good explanation why this either isn’t a good idea, or lacks in the C# languange?
abstract class Super
{
protected readonly int Field;
}
class Sub : Super
{
public Sub()
{
this.Field = 5; //Not compileable
}
}
PS: You can of course reach the same result by having assignment of the readonly fields in a protected constructor in the superclass.
The only reason I can see for this is because “it was just designed that way”, as per the spec:
The point of being read only is that it cannot be changed, if derived classes could modify then this would no longer be true and will violate encapsulation (by modifying the internals of another class).