override a property on a subclass in csharp

To override a property on a subclass in C#, you need to use the override keyword. Here's an example:

main.cs
public class ParentClass
{
    public virtual string MyProperty { get; set; } = "Parent Property";
}

public class ChildClass : ParentClass
{
    public override string MyProperty { get; set; } = "Child Property";
}
216 chars
10 lines

In this example, ChildClass inherits from ParentClass and overrides the MyProperty property with its own implementation. The override keyword specifies that the new implementation should be used instead of the one defined in the base class.

You can then use the MyProperty property on an instance of the ChildClass to access its value:

main.cs
ChildClass child = new ChildClass();
string childProperty = child.MyProperty; // returns "Child Property"
106 chars
3 lines

If you create an instance of the ChildClass and access its MyProperty property, you will get "Child Property" instead of "Parent Property".

gistlibby LogSnag