0

I'm attempting to build an 'Action' abstract class that will be used in many different ways. An Action, in my case, is just a simple repeatable task that is called by various 'Triggers'. I've also created an 'ActionArgs' class to be used as a structure to hold arguments for the Action to be performed. The default 'ActionArgs' object doesn't contain any arguments, which is intended to act as the default. However, I want to be able to create 'Action's and 'ActionArgs' that inherit from their respective parents, but I always want the base empty ActionArgs object to act as the default value for an optional parameter, as some Actions will have parameters, others might not. I'm having problems achieving this. I've tried a few things, but this is what I'm kind of going for:

public abstract class Action
{
    public string Name { get; private set; }

    public Action(string name) { Name = name; }

    public abstract bool PerformAction(ActionArgs args = ActionArgs.Empty);
}

public class ActionArgs
{
    public static readonly ActionArgs Empty = new ActionArgs();

    public ActionArgs() { }
}

In attempting this, I get an error on the PerformAction() definition, says that a default parameter value must be a compile-time constant. Why is this impossible to resolve this at compile time? I'm guessing it's because it is assuming the worst that you have some run-time variation in the constructor. In my case I clearly do not, but is there any way that I can approach this in a way that doesn't involve using null as the default parameter?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
codemann8
  • 372
  • 7
  • 29

1 Answers1

1

I would use a method overload:

public abstract class Action
{
    public string Name { get; private set; }

    public Action(string name) { Name = name; }

    public bool PerformAction() => PerformAction(ActionArgs.Empty);

    public abstract bool PerformAction(ActionArgs args);
}
ASh
  • 34,632
  • 9
  • 60
  • 82
  • Thanks! This works great! I don't know why the overlords mark questions as duplicates when they aren't. This answer here is great and isn't one of the answers on that question. I specifically ask for an answer that involves not setting it to null, which is extensively covered in that other question. – codemann8 Jun 04 '22 at 23:10
  • @codemann8, [the 2nd answer in the linked post](https://stackoverflow.com/a/18740465/1506454) suggests overloading – ASh Jun 05 '22 at 14:56