Search code examples
c#abstractderived-class

Derive Abstact Property


I have a base class that has an abstract property:

public class BottomClass {
  public abstract string Name {get;set;}
}

I now have a class that derives from that:

public class MiddleClass:BottomClass {
  public override string Name {get;set;}
}

what I now want is that the "MiddleClass" itself defines that property as abstract so that a class deriving from that will be forced to implement the property. The following code is not working that way:

public class MiddleClass:BottomClass {
  public abstract override string Name {get;set;} // Not possible that way
}

public class TopClass:MiddleClass {
  public override string Name {get;set;} ="tothetop";
}

Is there a way to achieve what I want?


Solution

  • If you define a property as abstract, you have to implement it in some non abstract class. So the only possible way to have the property in both classes is

    public abstract class BottomClass
    {
        public abstract string NameB { get; set; }
    }
    
    public abstract class MiddleClass : BottomClass
    {
        public abstract string NameM { get; set; } 
    }
    
    public class TopClass : MiddleClass {
        public override string NameB { get; set; }
        public override string NameM { get; set; }
    }
    

    As far as I can understand, your intention is to have 'Name' property in MiddleClass.

    Or don't implement it, as Damien commented above.