Search code examples
c#inheritanceinterfaceoverridingabstract-class

Is there a way to force a derived class to implement an abstract class or an interface nested in base class?


I have this abstract class:

public abstract class Task
{
  public string ID {get; set;}
  public string Name {get; set;}
  public abstract class Options{};

  public abstract void Execute();
}

I have other classes extending this class:

public class Copy : Task
{
  public override void Execute()
  {
    Console.Write ("running");
  }
}

I'd like each derived class to implement their own Options class so they can have their own parameters.

So Search class have to implement it's own Options class with the properties it needs, such as "includesubfolders", "casesensitive", etc..

Meanwhile Move task can implement it's own: "overwrite", etc..

Making properties and methods abstract in an abstract class force derived classes to implement their own but defining a nested abstract class or an interface in the same class does not force it's derived classes implement their own.

I can define each property individually in each derived class but that defeats the purpose since I like to query the properties in Task.Options later in the Execute method.

I tried dynamic object as well, but that brought whole other issues.


Solution

  • You can use a generic

    public abstract class Options{};
    
    public class CopyOptions : Options
    {
    }
    
    public abstract class Task<T> where T : Options
    {
      public string ID {get; set;}
      public string Name {get; set;}
    
      public T Options { get; set; }
    
      public abstract void Execute();
    }
    
    public class Copy : Task<CopyOptions>
    {
        public override void Execute()
        {
            Console.Write("running");
        }
    }