1

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.

Ultroman the Tacoman
  • 642
  • 1
  • 10
  • 16

1 Answers1

1

The compiler doesn't allow you to access any instance members before the object is fully constructed (i.e. all field initializers have run).

To get around this you can initialize MyAction in the class constructor, which will run after all the field initializers.

Edit: To reply to the second part of your question:

OnButton1Down += MyNonStaticFunction();

You're calling MyNonStaticFunction, not converting it to a delegate! Remove the () and it'll work better!

Chris
  • 5,442
  • 17
  • 30