1

I am trying to add a listener to an event through a function.

event Action ExampleEvent; void AddListener(Action emitter, Action receiver) { emitter += receiver; } 

Then somewhere I call it like this:

AddListener(ExampleEvent, () => Console.WriteLine("Example event received")); ExampleEvent?.Invoke(); 

But there is no output. I don't see what's missing.

0

1 Answer 1

2

You should use ref keyword like this.

event Action ExampleEvent; void AddListener(ref Action emitter, Action receiver) { emitter += receiver; } // Usage AddListener(ref ExampleEvent, () => Console.WriteLine("Example event received")); ExampleEvent?.Invoke(); 

Because Action instances are like a pointer (or a list of pointers) to a function(s) and they will be passed by value as a parameter. So, in order to pass them by reference, you need to use the ref keyword.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.