How to pass a System.Action by reference?
A delegate type is an immutable reference type, like a string:
s += "\n";
s
is now a reference to a different object. If you pass it to a method, the method gets a reference to this object, not to whatever object s
may refer to next. This lambda returns, and will continue to return, whatever object s
refers to when the lambda is called:
() => s;
The same applies with a += () => {};
: a
is referencing a different object afterwards, but you can create a lambda which executes the current value of a
, whatever that may be.
Hence:
new Class1().StartAsyncOperation(() => action());
Whatever you to do action
after that point, the lambda you passed in has a reference to the current value of action
.
Try it at home:
Action a = () => Console.Write("a");
// This would print "a" when we call b() at the end
//Action b = a;
// This prints "a+" when we call b() at the end.
Action b = () => a();
a += () => Console.Write("+");
b();