Feb 16, 2008

Use closure for event handler.

This is a sample program.
A number displayed on a label increases when a button is clicked.


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

this.button1.Click += new EventHandler(button1_Click);
}

int num = 0;

void button1_Click(object sender, EventArgs e)
{
this.label1.Text = num.ToString();
num++;
}
}


This code uses a member field "num".


I rewrite this code using closure.


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

this.button1.Click += make_button1_Click(0);
}

EventHandler make_button1_Click(int num)
{
return delegate(object sender, EventArgs e)
{
this.label1.Text = num.ToString();
num++;
};
}
}


This code uses no member field.
Closure memorize the variable "num".

No comments: