Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Closure binding

Tags:

closures

c#

Given the following, when is foo bound?

 System.Timer t = new System.Timer( (a)=>{
    var foo = Messages.SelectedItem as FooBar;
 });

Is it bound then the anonymous method is executed, or when the method is defined?

like image 551
Alan Avatar asked Apr 11 '26 12:04

Alan


2 Answers

foo is not bound at all, as it's internal to the anonymous method. It will call Messages.SelectedItem. If Messages is an instance property, what is bound is the 'this' instance, which is used to get at Messages.

like image 146
Dan Bryant Avatar answered Apr 13 '26 02:04

Dan Bryant


Never, because of the compile-time error you would get due the absence of a System.Timer class in the BCL. Assuming you wanted a System.Threading.Timer then the closure will be bound/captured at the moment this constructor is called i.e. the method is defined. If you want to bind it when the method is executed you need another constructor overload and pass a state.

var t = new System.Threading.Timer(a =>
{
    var foo = a as FooBar;
}, Messages.SelectedItem, -1, -1);

Now when the callback runs it will use the Messages.SelectedItem value at the moment this callback executes.

like image 23
Darin Dimitrov Avatar answered Apr 13 '26 04:04

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!