Friday, 3 May 2013

Difference between delegate() { } and delegate { }

Many times we use delegates such as Action<T> or Func<T, TResult> and we do not want to pass in any argument. For instance, let’s take the Click event’s delegate EventHandler.

The EventHandler delegate expects two arguments – sender and event args, but there are instances when we do not use these parameters in the method. Now when we are writing anonymous method we need to specify these arguments. Code:

 button1.Click +=
delegate(object sender, EventArgs args)
{
MessageBox.Show("Got Clicked!");
};

But, we also have another option. Code:

 button1.Click +=
delegate
{
MessageBox.Show("Got Clicked!");
};

And it works! So we do not use () after the keyword delegate, and it runs perfectly.

But do note, if we are using lambda this option is not available.

 button1.Click += () => //ERROR
{
MessageBox.Show("Got Clicked!");
};

The code above would give the error: Delegate 'System.EventHandler' does not take '0' arguments. It is because using “() =>” means a method without parameters.

With lambda we have to specify (s, e) =>. Code:

 button1.Click += (s, e) =>
{
MessageBox.Show("Got Clicked!");
};

1 comment:

Note: only a member of this blog may post a comment.