Interview Tips Interview Tips, Interview Questions and Answers

27Nov/100

Using Delegate Parameters with Anonymous Methods

Many event handlers need to use the parameters of the delegate they are based on. The previous example didn't use those parameters, so it was more convenient to not declare them, which C# allows. Listing 21-2 shows you how to use parameters if you need to.
// Using Parameters with Anonymous Methods

using System;
using System.Windows.Forms;

public partial class Form1 : Form
{
public Form1()
{
Button btnHello = new Button();
btnHello.Text = "Hello";

btnHello.Click +=
delegate
{
MessageBox.Show("Hello");
};

Button btnGoodBye = new Button();
btnGoodBye.Text = "Goodbye";
btnGoodBye.Left = btnHello.Width + 5;

btnGoodBye.Click +=
delegate(object sender, EventArgs e)
{
string message = (sender as Button).Text;
MessageBox.Show(message);
};

Controls.Add(btnHello);
Controls.Add(btnGoodBye);
}
}

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.