override a static property on a subclass in csharp

To override a static property on a subclass in C#, you can use the new keyword to shadow the parent class's property with a new one in the child class.

Here's an example:

main.cs
public class ParentClass
{
    public static int MyProperty { get; set; } = 10;
}

public class ChildClass : ParentClass
{
    public new static int MyProperty { get; set; } = 20;
}
182 chars
10 lines

In the example above, we create a ParentClass with a static property MyProperty set to 10. Then we create a ChildClass that inherits from ParentClass, but we use the new keyword to declare a new static property called MyProperty, and set it to 20.

If we were to access ParentClass.MyProperty, we'd get 10, while if we were to access ChildClass.MyProperty, we'd get 20.

main.cs
Console.WriteLine(ParentClass.MyProperty);  // output: 10
Console.WriteLine(ChildClass.MyProperty);   // output: 20
116 chars
3 lines

Note that this approach "shadows" the parent class's property, rather than overriding it. This means that if you were to cast the child class to the parent class, you'd still get the parent class's property value.

main.cs
ChildClass childObj = new ChildClass();
ParentClass parentObj = childObj;

Console.WriteLine(parentObj.MyProperty);  // output: 10
131 chars
5 lines

gistlibby LogSnag