Why is it impossible to override a getter-only property and add a setter? [closed]

I think the main reason is simply that the syntax is too explicit for this to work any other way. This code:

public override int MyProperty { get { ... } set { ... } }

is quite explicit that both the get and the set are overrides. There is no set in the base class, so the compiler complains. Just like you can’t override a method that’s not defined in the base class, you can’t override a setter either.

You might say that the compiler should guess your intention and only apply the override to the method that can be overridden (i.e. the getter in this case), but this goes against one of the C# design principles – that the compiler must not guess your intentions, because it may guess wrong without you knowing.

I think the following syntax might do nicely, but as Eric Lippert keeps saying, implementing even a minor feature like this is still a major amount of effort…

public int MyProperty
{
    override get { ... } // not valid C#
    set { ... }
}

or, for autoimplemented properties,

public int MyProperty { override get; set; } // not valid C#

Leave a Comment