Search code examples
c#abstract-class

Defining an abstract property that's settable by parent class


I'm not very familar with C# or abstract classes so this is likely a simple fix. I have an abstract class with a nullable Action property:

public abstract class MyAbstractClass {
    public abstract Action<MyType>? myAbstractAction { get; set; }
}

And the concrete class:

public class MyConcreteClass: MyAbstractClass {
    // This gives me a warning that I'm "hiding" the abstract property
    public override Action<MyType>? myAbstractAction = null;
}

The Action property will only be set by the parent of the concrete class:

public classs MyParentClass {
    public MyConcreteClass concreteClassInstance;

    public MyParentClass(MyConcreteClass concreteClassInstance) {
        this.concreteClassInstance = concreteClassInstance;
        this.concreteClassInstance.myAbstractAction = //...
    }
}

My issue is that I'm not sure how to define the Action in MyConcreteClass. The line I used above that gives a default value of null causes an error saying it "hides inherited member" which doesn't seem like what I want. I think it expects me to provide actual get/set blocks but I don't think that will work for me since it's the outer class that determines what the Action does. I kinda feel like I may be using the wrong tool for the job here so would appreciate some direction from someone more familiar with the language.


Solution

  • The reason why you getting that warning is that in base class you declared a property myAbstractAction, and in child class you declared a field myAbstractAction. So there are two members with the same name.

    This property:

    public abstract Action<MyType>? myAbstractAction { get; set; }
    

    Should be overridden like that:

    public override Action<MyType>? myAbstractAction { get; set; }
    

    You're supposed to type that get and set.