I detected the feature of C# that it is possible to use an Action or Func like an event. What I mean is, that I can do following:
Action aAction;
aAction = DoSomething;
aAction += DoAnotherting;
// execute the action -> both functions will be executed
aAction();
aAction -= DoSomething; // unsubscribe on function
I was not aware of this, thought using += is only possible for events. In the first moment this looks quite well, as I do not have to use the event keyword and I can also call this action from outside of the owner class (what is not possible for events). But I'm wondering, are there any good examples for such a use or is it only bad practice?
A complete example is shown here:
[TestMethod]
public void DummyTest()
{
DummyClass myInstance = new DummyClass();
int i = 0;
Action action1 = () => i++;
Action action2 = () => i += 2;
Func<int> func1 = () => 5;
myInstance.MyFunc += () => 3;
myInstance.MyFunc += func1;
Assert.AreEqual(5, myInstance.MyFunc?.Invoke() );
myInstance.MyFunc -= func1;
Assert.AreEqual(3, myInstance.MyFunc?.Invoke() );
myInstance.MyAction = action1;
myInstance.MyAction += action2;
myInstance.MyAction?.Invoke();
Assert.AreEqual(3, i);
myInstance.MyAction -= action1;
myInstance.MyAction?.Invoke();
Assert.AreEqual(5, i);
myInstance.MyAction = () => i = 0;
myInstance.MyAction?.Invoke();
Assert.AreEqual(0, i);
}
class DummyClass
{
public Action MyAction;
public Func<int> MyFunc;
}