A function that returns a value:
public object ReturnValue() { return new object(); }
Func<object> funcReturnValue = ReturnValue;
A function that retuns a function that returns a value:
public Func<object> ReturnFunc() { return ReturnValue; }
Func<Func<object>> funcReturnFunc = ReturnFunc;
So far, so good. I'm having trouble with a function that returns itself:
public *something* ReturnSelf() { return ReturnSelf; }
Func<*something*> funcReturnSelf = ReturnSelf;
Clearly, *something* is going to be a Func<T> of some kind, but I'm not sure what.
At first glance I guess it's going to be infinity recursive, since ReturnSelf
returns a function that returns a function that returns a function...
Context: A state machine using functions for states. It works fine using a class variable to keep the current state:
private Action _currentState;
private void StateOne() {
if (IsTuesday) {
_currentState = StateTwo;
}
}
prvivate void StateTwo() {
if (IsRaining) {
_currentState = StateOne;
}
}
private void StateEngine() {
while (true) {
_currentState();
// set tuesday/raining/etc.
}
}
...but that feels too much like keeping state in a global. I'd far prefer something closer to:
private Func<*somthing*> StateOne() {
if (IsTuesday) {
return StateTwo;
} else {
return StateOne;
}
}
prvivate Func<*something*> StateTwo() {
if (IsRaining) {
return StateOne;
} else {
return StateTwo;
}
}
private void StateEngine() {
Func<*something*> currentState = StateOne;
while (true) {
Func<*something*> nextState = currentState();
// set tuesday/raining/etc.
currentState = nextState;
}
}
Any ideas? Or should I just stick with the working solution?