I’m trying to make a design for some sort of IExecutable interface. I will not get into details, but the point is that I have several Actions that need to be executed from a base class. They may take different parameters (no big deal), and they may/may not return a value.
So far, this is my design:
public abstract class ActionBase
{
// ... snip ...
}
public abstract class ActionWithResultBase<T>: ActionBase
{
public abstract T Execute();
}
public abstract class ActionWithoutResultBase: ActionBase
{
public abstract void Execute();
}
So far, each of my concrete actions need to be a child from either ActionWithResultBase or ActionWithoutResult base, but I really don’t like that. If I could move the definition of Execute to ActionBase, considering that the concrete class may or may not return a value, I will have achieved my goal.
Someone told me this could be done with using Func and Action, for which I totally agree, but I can’t find a way to have that into one single class so that the caller would know if the action is going to return a value or not.
Brief: I want to do something like:
// Action1.Execute() returns something.
var a = new Action1();
var result = a.Execute();
// Action2.Execute() returns nothing.
var b = new Action2();
b.Execute();
If you want a lightweight solution, then the easiest option would be to write two concrete classes. One will contain a property of type
Actionand the other a property of typeFunc<T>:Then you can construct the two types like this:
If you don’t want to make
Actionproperty read/write, then you could pass the action delegate as an argument to the constructor and make the property readonly.The fact that C# needs two different delegates to represent functions and actions is quite annoying. One workaround that people use is to define a type
Unitthat represents “no return value” and use it instead ofvoid. Then your type would be justFunc<T>and you could useFunc<Unit>instead ofAction. TheUnittype could look like this:To create a
Func<Unit>value, you’ll write: