Alex Rivera | Logout

readonly-fields as targets from subclass constructors

Asked 2011-10-09T20:41:24.577
24

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.

Edit
Report

1 Answer

13
public class Father
{
    protected readonly Int32 field;

    protected Father (Int32 field)
    {
        this.field = field;
    }
}

public class Son : Father
{
    public Son() : base(5)
    {

    }
}

You may try something like this instead!

answered 2011-10-09T20:59:51.633

Your Answer