Skip to main content

Command Palette

Search for a command to run...

TIL C# property overrides are separate for getters and setters

Updated
1 min read
TIL C# property overrides are separate for getters and setters

I recently hit an interesting gotcha with some code in a C# codebase i was working with. It baffled me because I didn’t understand how this could compile.

MyClass.Foo has a getter but no setter, yet an instantiated MyClass can have the Foo property set! How is that happening, and what does it do?

public class MyClass : LibraryClass
{
    public string OtherProperty { get; set; }

    public override string Foo => OtherProperty; // getter-only, no way to set the value
}

public class MyService
{
    public void DoThing()
    {
        var myClass = new MyClass
        {
            // How does this compile? There is no setter for Foo.
            Foo = "I'm setting this property"
        };
    }
}

It turns out that even though the Foo property only has a getter defined within MyClass, there’s a setter on the Foo property within LibraryClass, and this means it’s valid to write to the property within MyService.

The reason is that the override keyword is only overriding the getter, not the whole property. The setter therefore still exists in its original form, and can be used. What this does it write the set value to the backing field, but it’s not possible to get that value back out and do anything with it. It’s not useful, but it is valid and it does compile.

More from this blog

T

Tim talks tech

76 posts