0

I am initializing a mutable class instance as a local variable with new keyword. Then I pass this object as a parameteter to a delegate. Is this variable's lifetime extended by the delegate? Do other threads use this variable or create their own instances? I may be asking the obvious but I want to be sure.

public void DoSometing(Action<Foo> action)
{
    Foo foo = new Foo();
    action.Invoke(foo);
}
Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156

1 Answers1

3

Whenever you pass local variables that "escape" the method one way or another, you do extend its lifetime. In C# you will never operate upon a variable that contains a reference to a non-existant object -- the concept makes no sense in a managed environment.

So yes, foo will continue to live on, and you will need to be concerned with thread-safety in exactly the same way as if you simply called another ordinary method. In this scenario, lambdas do not change the complexion of the problem.

However, sometimes this can be more subtle, especially if you return a lambda -- one which closes over local variables. In such a scenario, all the variables you reference from within the lambda live on in the same way as foo.

Community
  • 1
  • 1
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
  • Ok that's right but each lambda expression will use a new Foo instance right? – Ufuk Hacıoğulları Jun 04 '12 at 00:20
  • In your example, the *caller* will provide *either* a lambda or a method reference. In either scenario, each time `DoSomething` is invoked, a new instance of `foo` will be passed to `action`. To be precise there is actually no lambda in `DoSomething` at all, merely an instance (`action`) of the *delegate* `Action`. – Kirk Woll Jun 04 '12 at 00:27