override a getter on a subclass in csharp

To override a getter on a subclass in C#, you need to follow these steps:

  1. Declare a property with the same name and return type as the property you want to override in the base class.
  2. Use the override keyword followed by the access modifier of the property (public, private, etc) and the keyword get.
  3. Inside the getter, call the base class's getter by using the base keyword followed by the property name.
  4. Add any additional logic you need to the getter.

Here's an example:

main.cs
public class MyBaseClass
{
    public virtual string MyProperty { get; } = "Hello world!";
}

public class MySubclass : MyBaseClass
{
    public override string MyProperty
    {
        get
        {
            // Call the base class's getter.
            var baseValue = base.MyProperty;

            // Add additional logic to the getter.
            return $"Override: {baseValue}";
        }
    }
}
405 chars
20 lines

In this example, MySubclass overrides the MyProperty getter in MyBaseClass. The overridden property calls the base class's getter and then adds "Override: " to the beginning of the returned string.

gistlibby LogSnag