I have just been watching a TekPub video on Lambda’s and the code was similar to such:
class Foo{
void DoSomething();
}
static void Bar(Foo item, Action<Foo> action){
return action.Invoke(item);
}
And then within Main:
Bar(new Foo(), x=>x.DoSomething();
My question is, is the Foo object just within scope for that call to Bar? Is the object destroyed once that method has been called?
Thanks.
In this particular case, what happens is that the
fooobject is passed, along with your delegate, to the Bar method. The Bar method invokes the action, which calls DoSomething on foo, then returns.Since the method Bar doesn’t return the object you pass to it, nor the result of calling the delegate, and the code in question doesn’t store the object reference anywhere, the object
foothat you created is now eligible for garbage collection once Bar returns.Exactly when memory for that object will be reclaimed depends on when GC runs, but at some point after Bar has returned, the memory allocated to the object will be reclaimed. It will not happen immediately, ie. as part of Bar returning.