Events. Examples of using an anonymous method and a lambda expression as an event. Event handlers that are used in a .NET environment

Events. Examples of using an anonymous method and a lambda expression as an event. Event handlers that are used in a .NET environment

 


Content


1. An example of using an anonymous method as an event handler

The example demonstrates the use of an anonymous method as an event handler for an application created using the Windows Forms Application template. In an anonymous method, the area of a circle is calculated based on a given radius r.

The sequence of steps is as follows.

In some class, let the delegate type and event be declared as follows:

// Declare the type of CalcFigure delegate
delegate double CalcFigure(double r);

// declare a CF event
event CalcFigure CF;

Then, the program code demonstrating the event will look like:

// Use an anonymous method as an event handler
CF += delegate(double r)
{
    // the method calculates the area of a circle of radius r
    const double Pi = 3.1415;
    double res;
    res = Pi * r * r;
    return res;
};

// test
double R = 3.0;
double Res;
Res = CF(R);   // Res = 28.2735

If the application is created using the Windows Forms Application template, you can perform all these actions, for example, in the event handler of the click event on the button. In this case, the program code of the form module will be as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TrainEvents03
{
    public partial class Form1 : Form
    {
        // Declare the type of CalcFigure delegate
        delegate double CalcFigure(double r);

        // declare a CF event
        event CalcFigure CF;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Use an anonymous method as an event handler
            CF += delegate(double r)
            {
                // the method calculates the area of a circle of radius r
                const double Pi = 3.1415;
                double res;
                res = Pi * r * r;
                return res;
            };

            // test
            double R = 3.0;
            double Res;
            Res = CF(R);   // Res = 28.2735
            label1.Text = Res.ToString();
        }
    }
}

 

2. An example of using a lambda expression as an event handler

The following code demonstrates the use of a lambda expression as an event handler. As in the previous example, the area of the circle is calculated. The steps for demonstrating lambda expressions are the same as in the previous example.

First, in the class, you need to declare the delegate type and event:

// Declare the type of CalcFigure delegate
delegate double CalcFigure(double r);

// declare a CF event
event CalcFigure CF;

Then in some method of this class, you can generate the following code, which demonstrates the use of a lambda expression

// Using a lambda expression as an event handler
CF = (r) =>
{
    // the area of a circle of radius r is calculated
    double res;
    res = 3.1415 * r * r;
    return res;
};

// test
double RR, Res;
RR = 2.0;
Res = CF(RR);

 

3. What are the requirements for event handlers to ensure compatibility with the .NET environment?

In order for the own event handlers to be compatible with the .NET environment, they must have two parameters:

  • the first parameter is a reference to the object that forms the event;
  • the second parameter is a parameter of type EventArgs.

 

4. What is the general form of an event handler that is compatible with the .NET environment?

The general form of the .NET-compatible event handler is:

void name(object sender, EventArgs e)
{
    // ...
}

where

  • name – the name of the method of the event handler that is compatible with the. NET environment;
  • EventArgs – class containing additional information about the event.

In this case, the type of the delegate, when declared, must have exactly the same signature.

 

5. An example that demonstrates the use of an event that is compatible with the .NET environment

First, you need to declare the type of delegate whose signature is compatible with the .NET environment.

// declare the delegate type
delegate void MyTypeDelegate(object sndr, EventArgs e);

The next step is to declare an event:

// declare an event
event MyTypeDelegate EMD;

The declaration of methods that are compatible with the event can be as follows:

// Declaring the event handler methods
void EventHandler1(object sndr, EventArgs e)
{
    // commands, instructions
    // ...
}

void EventHandler2(object sndr, EventArgs e)
{
    // commands, instructions
    // ...
}

void EventHandler3(object sndr, EventArgs e)
{
    // commands, instructions
    // ...
}

Demonstration of using an event from a certain method, for example, a click event handler on button1_Click():

private void button1_Click(object sender, EventArgs e)
{
    // Demonstration of an event that is compatible with the .NET Framework

    // Generate a list of methods that are called when the event runs
    EMD = EventHandler1;
    EMD += EventHandler3;
    EMD += EventHandler2;

    // Running an Event
    EMD(this, e);

    // Another way to run the button1_Click event
    EMD(sender, e);
}

All the code of the Form1.cs module that demonstrates this example is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TrainEvents05
{
    public partial class Form1 : Form
    {
        // declare the delegate type
        delegate void MyTypeDelegate(object sndr, EventArgs e);

        // declare an event
        event MyTypeDelegate EMD;

        public Form1()
        {
            InitializeComponent();
            label1.Text = "";
        }

        // Declaring the event handler methods
        void EventHandler1(object sndr, EventArgs e)
        {
            label1.Text += "EventHandler1 ";
        }

        void EventHandler2(object sndr, EventArgs e)
        {
            label1.Text += "EventHandler2 ";
        }

        void EventHandler3(object sndr, EventArgs e)
        {
            label1.Text += "EventHandler3 ";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Demonstration of an event that is compatible with the .NET Framework

            // Generate a list of methods that are called when the event is run
            EMD = EventHandler1;
            EMD += EventHandler3;
            EMD += EventHandler2;

            // Running an Event
            EMD(this, e);

            // Another way to start the button1_Click event
            EMD(sender, e);
        }
    }
}

 

6. What is the purpose of the generalized EventHandler<TEventArgs> delegate

The generic delegate EventHandler <TEventArgs> is implemented in the .NET environment. This delegate is intended to replace your own event delegate.

For example, in the previous paragraph, the event

event MyTypeDelegate EMD;

It can be replaced by a code

event EventHandler<EventArgs> EMD;

and you do not need to declare the type of delegate.

 

7. An example of code that uses the generalized delegate EventHandler, which is implemented in the .NET environment

In this example, exactly the same code is executed as in paragraph 5. Only instead of its own delegate type used generic delegate EventHandler, using which an event is declared.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TrainEvents05
{
    public partial class Form1 : Form
    {
        // You do not need to declare your own delegate type
        // Declare an event using the EventHandler generic delegate
        event EventHandler<EventArgs> EMD;

        public Form1()
        {
            InitializeComponent();
            label1.Text = "";
        }

        // Declaring an event handler methods
        void EventHandler1(object sndr, EventArgs e)
        {
            label1.Text += "EventHandler1 ";
        }

        void EventHandler2(object sndr, EventArgs e)
        {
            label1.Text += "EventHandler2 ";
        }

        void EventHandler3(object sndr, EventArgs e)
        {
            label1.Text += "EventHandler3 ";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Demonstration of an event that is compatible with the .NET Framework
            // Generate a list of methods that are called when the event is run
            EMD = EventHandler1;
            EMD += EventHandler3;
            EMD += EventHandler2;

            // Running the event
            EMD(this, e);

            // Another way to run the button1_Click event
            EMD(sender, e);
        }
    }
}

In the above code, the string

event EventHandler<EventArgs> EMD;

can be replaced by a simplified string

event EventHandler EMD;

 

8. What is the purpose of the Empty object from the EventArgs class?

In some cases in the .NET environment when you working with events, the EventArgs parameter is optional. In these cases, it is more appropriate to use the Empty object from the EventArgs class. This is done to simplify the creation of the code.

So, in the previous example, the string

// Run the event
EMD(this, e);

// Another way to run the button1_Click event
EMD(sender, e);

can be replaced

// Run the event
EMD(this, EventArgs.Empty);

// Another way to run the button1_Click event
EMD(sender, EventArgs.Empty);

 


Related topics