Implementing an Anonymous Method:
-Open windows form application
public Form1()
{
InitializeComponent();
Button
btnHello = new Button();
btnHello.Text = "Hello";
btnHello.Click +=
delegate
{
MessageBox.Show("Hello");
};
Controls.Add(btnHello);
}
Using Parameters with Anonymous Methods
Button btnHello = new Button();
//Button
btnGoodBye = new Button();
btnHello.Text = "Hello";
btnHello.Click +=
delegate(object sender, EventArgs
e)
{
string
message = (sender as Button).Text;
MessageBox.Show(message);
};
Controls.Add(btnHello);
Why should we use Anonymous method?
We can reduce the code by preventing delegate instantiation
and registering it with methods. It increases the
readability and maintainability of our code by keeping the
caller of the method and the method itself as close to one another as possible
No comments:
Post a Comment