Brahim Benbachir

Look and See#
posts - 2, comments - 2, trackbacks - 1

My Links

News

Archives

Post Categories

News

SQL Server 2005

Friday, September 29, 2006

A case where it's usefull to use anonymous methods feature of C# 2.0

In C# 1.0, when you wanted to start a thread, you were obliged to write code like this:

private void button1_Click(object sender, EventArgs e)
{
  Thread
t = new Thread(new ThreadStart(Method));
  t.Start();
}

void Method()
{
 
MessageBox.Show("Thread has started"
);
}

In C# 2.0, you can use the new feature that are anonymous methods

private void button1_Click(object sender, EventArgs e)
{

  Thread
t2 = new Thread(delegate() {
                                   
MessageBox.Show("Thread has started"
);
                                   
});
  t2.Start();
}

Anonymous methods are usefull when only a delegate will suffice, preventing us from polluting our class definition with small methods that are used only once.

Same thing with Thread initialization but with parameters:

private void button1_Click(object sender, EventArgs e)
{
  Thread
t3 = new Thread(delegate(object o) {
                                            
MessageBox
.Show(o.ToString());
                                            });
  t3.Start(
"Thread has started with parameters");
}

PS: If you still want to have methods instead of anonymous methods, you can use this shorter sentence in C# 2.0:

Thread
t = new Thread(Method);
t.Start();

This is known as delegate inference. it permits you to make a direct assigment of a method name to a delegate and the compiler can infer it.

posted @ Friday, September 29, 2006 10:44 AM | Feedback (0) | Filed Under [ .NET ]

Thursday, September 28, 2006

Unpacking...

Hi everyone,

I'm starting a new blog here. You can have access to my old blog at this place

Regards

posted @ Thursday, September 28, 2006 11:18 AM | Feedback (0) |

Powered by: