Darren Young
Darren Young

Reputation: 11090

C# Lambda Object Scope

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.

Upvotes: 0

Views: 285

Answers (2)

Femaref
Femaref

Reputation: 61437

Yes, it should be disposed of once the method returns as none of the operations produce an additional reference.

However, this isn't the general case, it really depends on what the method does with it - if it creates a new object with a reference to the inline created one, it can live after the method returned. In this case the Action<T> could add the Foo to a dictionary or list of some sort which would mean that it won't be garbage collected, as there are still references to it.

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391376

In this particular case, what happens is that the foo object 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 foo that 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.

Upvotes: 2

Related Questions