This is probably a duplicate, but I cannot find any threads which explain this behavior. At least not pertaining to Action
(which are basically Func's with no return type). It's to do with static references.
Look at these two examples. I'm merely trying to subscribe to the System.Action OnButton1Down
, to make it call a non-static function when the Action
is invoked with .Invoke()
.
Why does the first method work, but not the second or third ones? I would much rather have the Action
saved/prepared, so I can also unsubscribe it again without trickery, by simply doing: OnButton1Down -=
System.Action OnButton1Down;
void MyNonStaticFunction() { }
// This example works
void MyFirstFunction()
{
OnButton1Down += () => { MyNonStaticFunction(); };
}
// This example gives the following error on "MyNonStaticFunction()":
// "A field initializer cannot reference the non-static field, method
// or property MyNonStaticFunction()."
System.Action MyAction = () => { MyNonStaticFunction(); };
void MySecondStartFunction()
{
OnButton1Down += MyAction;
}
// This example is to show what happens, if I just try to subscribe the raw
// method to the Action, as suggested in the comments.
// It gives the following error on "MyNonStaticFunction()":
// "Cannot implicitly convert type 'void' to type 'System.Action'."
void MyThirdStartFunction()
{
OnButton1Down += MyNonStaticFunction();
}
I sort of understand that the errors make sense, but I don't see why the first example is OK. I would much rather be able to do either of the other examples.