While looking up the answer to this question: "Why is an out parameter not allowed within an anonymous method?" I've got a little lost about how do lambda expression and anonymous methods actually work.
In the comments JaredPar states that "Imagine for instance that the out parameter referred to a local variable on the stack. The lambda can execute at any arbitrary point in the future and hence could execute when that stack frame was no longer valid".
I pointed out if wouldn't that be the case with any other variable... which basically make me wonder what to I really know about lambda expressions.
The thing I have in mind is something like this:
public void Foo(ComplexObject val, out SomeDelegate outDelegate)
{
ComplexObject obj = new ComplexObject(val)
SomeDelegate = delegate(int other) { return (obj.value * other); }
}
public void Bar()
{
SomeDelegate MyDel = null;
Foo(5, out MyDel);
int finalRes = MyDel(100);
// Whatever
}
In that situation I don't really know what's happening. obj is a reference on the stack which would no longer be valid on method return so the annonymous method should be able (if that works) to actually know that's a reference type and copy the reference instead of the value, if it does... why wouldn't ref params work if the "use case" is more or less the same?