0

TLDR; Why does this work.

    Queue<Action> queue = new Queue<Action>();
    queue.Enqueue(() => Load("Scene01"));

But not this.

    Queue<Action> queue = new Queue<Action>();
    queue.Enqueue(Load("Scene01"));

I was trying to create a simple load system that allow scheduling multiple loads at the same time. Found it would be simple storing request as action which then gets added to a queue that some function makes its way through.

The loading function I use is overloaded, and thus the actions created will differ from one another. At first I though I'd be require to create some kind of generic system that could take different actions, but then I found this.

Storing a list of methods in C#

Question Why is it that you can pass a function that doesn't match the action using a lambda expression?

Queue<Action> queue = new Queue<Action>();

private void Load() { }

private void Load(string n) { }

private void QueueLoad()
{
    // This match action signature.
    queue.Enqueue(Load);

    // This does not match, nor work.
    queue.Enqueue(Load("Scene01"));

    // Adding lambda expression and it works. Why?
    queue.Enqueue(() => Load("Scene01"));
}
adwerk
  • 3
  • 1
  • Your second code block doesn't work because you are calling the `Load` method and returning it's result to store in the queue. – DavidG Sep 28 '18 at 09:28
  • Ah, now I see. I notice that changing "Load" to "Load()" gives the same result. So I guess the lambda make sure its the actual function being passed. Thanks a lot man, it had me puzzled. – adwerk Sep 28 '18 at 09:37

1 Answers1

1
queue.Enqueue(Load);

This works because Load is a method group and can be converted to Action.

queue.Enqueue(() => Load("Scene01"));

This works because the lambda expression takes no arguments and returns nothing, hence implicitly convertible to Action.

queue.Enqueue(Load("Scene01"));

This does not work because Load("Scene01") is a method call, and the method doesn't return anything, you are trying to pass void into Enqueue method.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184