C#. Windows Forms. An example of solving a problem that calculates the characteristics of geometric figures using delegates




An example of solving a task that calculates the characteristics of geometric figures using delegates

This example demonstrates the use of C# delegates to solve a task in which the characteristics of geometric shapes are calculated.


Contents


Search other websites:

Task

In an application of the Windows Forms Application type, declare the type of the delegate that refers to the method. The requirements for the method signature are as follows:

  • the method takes a variable of type double;
  • the method returns a double value, which is the result of the calculation.

Implement a calling of methods with a delegate, which take the radius R and compute:

  • the circumference by formula D = 2 · π · R;
  • area of the circle by the formula S = π · R2;
  • volume of a sphere. Formula: V = 4/3 · π · R3.

Methods must be declared as static (with the keyword static).

 


Considerations

To work with the program, choose the following names:

  • the delegate type name is CalcFigure;
  • the delegate name – CF;
  • the name of the method that calculates the circumference – Get_Length();
  • the name of the method that computes the area of the circle – Get_Area();
  • the name of the method that computes the volume of a sphere is Get_Volume().

The delegate type and method type declaration is implemented in the Form1 class of the main application form.

 


Instructions

1. Run Microsoft Visual Studio. Create a project using a Windows Forms Application template

Create a project using the Windows Forms Application template. The name of the module of the main form “Form1.cs”. You can specify the project name, for example, “Delegates01”. The instance name of the Form1 application object.

An example of creating a project using the Windows Forms Application template is described in detail in the topic:

The window for the newly created application form is shown in Figure 1.

C#. Windows Forms Application. The window of main form of application

Figure 1. The window of main form of application

After the project is created, the text of the main application form module 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 Delegates01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

 

2. Development the form of application

Place the following controls on the form of application:

  • four controls of the Label type. As a result, 4 instances (objects) of Label class with names label1, label2, label3, label4 will be created;
  • a control of TextBox type with the name textBox1;
  • a control of Button type with the name button1.

With the help of Properties window set the following properties of the controls:

  • in the control label1, property Text = “R = “ (label1.Text = “R = “);
  • label2.Text = “Circumference = “;
  • label3.Text = “Area of a circle = “;
  • label4.Text = “Volume of a sphere = “;
  • in the control Form1 (main form of application) property Text = “Calculate”;
  • in Form1 property StartPosition = CenterScreen;
  • in the control button1 property Text = “Calculate”.

After the performed actions, the form of the application will have the view as shown in Figure 2.

C#. Windows Forms Application. The form of application after configuration and placement of controls

Figure 2. The form of application after configuration and placement of controls

 

3. Writing the program code

3.1. Declaring the delegate type

The delegate type is named CalcFigure and declared in the Form1 class (the file “Form1.cs”) before the constructor of Form1() form.

Тип делегата носит имя CalcFigure и объявляется в классе Form1 (файл “Form1.cs”) перед конструктором формы Form1().The text of the declaration of delegate is as follows:

// Declaring the type of delegate named CalcFigure
delegate double CalcFigure(double r);

When you declare a delegate type, the delegate keyword is used.



 

3.2. Declaration of methods for calculating the characteristics of geometric shapes

Methods are declared in the form class after the Form1() constructor is implemented.

Методы объявляются в классе формы после реализации конструктора формы Form1().In accordance with the condition of the task, the methods in the class are declared as static with the static keyword.

After the methods are declared, the text of the module “Form1.cs” looks like this:

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 Delegates01
{
    public partial class Form1 : Form
    {
        // Declaring a CalcFigure delegate type
        delegate double CalcFigure(double r);

        public Form1()
        {
            InitializeComponent();
        }

        // declaring static methods in a class
        // the circumference
        public static double Get_Length(double r)
        {
            double length;
            length = 2 * 3.1415 * r;
            return length;
        }

        // area of a circle
        public static double Get_Area(double r)
        {
            double area;
            area = 3.1415 * r * r;
            return area;
        }

        // the volume of a sphere
        public static double Get_Volume(double r)
        {
            double volume;
            volume = 3.1415 * r * r * r * 4.0 / 3.0;
            return volume;
        }
    }
}

 

3.3. Programming the Click event, which is called when the button1 button is clicked (option 1)

The next step is programming the click event on the “Calculate” button (button1 control).

The text of the click event handler on button1 is as follows:

private void button1_Click(object sender, EventArgs e)
{
    double radius, length, area, volume;

    // read the radius
    radius = Convert.ToDouble(textBox1.Text);

    // call a delegate
    // construct a delegate
    CalcFigure CF = new CalcFigure(Get_Length);
    length = CF(radius); // 1. Calling the Get_Length() method

    CF = new CalcFigure(Get_Area);
    area = CF(radius); // 2. Calling the Get_Area() method

    CF = new CalcFigure(Get_Volume);
    volume = CF(radius); // 3. Calling the Get_Volume() method

    // output of result
    label2.Text = "Circumference = " + length.ToString();
    label3.Text = "Area of a circle = " + area.ToString();
    label4.Text = "Volume of a sphere = " + volume.ToString();
}

Let’s explain some fragments of the code.

The radius of the circle is read into the internal variable radius. Conversion from a string to text is done using the Convert class (the ToDouble() method).

The next step is to build a delegate named CF. This delegate is initialized with the value Get_Length. This means that the delegate refers to the Get_Length() method.

In the next steps, the CF delegate is redefined according to the methods Get_Area() and Get_Volume().

The next item displays a different implementation of the event handler.

 

3.4. Programming the Click event, which is called when the button1 button is clicked (option 2)

The click event handler on the button1 button can have another implementation, which is more obvious and simplified.

private void button1_Click(object sender, EventArgs e)
{
    double radius, length, area, volume;

    // read the radius
    radius = Convert.ToDouble(textBox1.Text);

    // calling the delegate
    // construct the delegate
    CalcFigure CF = Get_Length;
    length = CF(radius); // 1. Calling the Get_Length() method

    CF = Get_Area;
    area = CF(radius); // 2. Calling the Get_Area() method

    CF = Get_Volume;
    volume = CF(radius); // 3. Calling the Get_Volume() method

    // output of results
    label2.Text = "Circumference = " + length.ToString();
    label3.Text = "Area of a circle = " + area.ToString();
    label4.Text = "Volume of a sphere = " + volume.ToString();
}

In this case, the so-called group transformation of delegated methods occurs. With this transformation, the keyword new is omitted. The program code is simplified.

 

3.5. Text of module Form1.cs

The text of the whole module Form1.cs of the solution of this task (option 2) looks like:

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 Delegates01
{
    public partial class Form1 : Form
    {

        // Declaring a CalcFigure delegate type
        delegate double CalcFigure(double r);

        public Form1()
        {
            InitializeComponent();
        }

        // declaring static methods in a class
        // circumference
        public static double Get_Length(double r)
        {
            double length;
            length = 2 * 3.1415 * r;
            return length;
        }

        // area of a circle
        public static double Get_Area(double r)
        {
            double area;
            area = 3.1415 * r * r;
            return area;
        }

        // volume of a sphere
        public static double Get_Volume(double r)
        {
            double volume;
            volume = 3.1415 * r * r * r * 4.0 / 3.0;
            return volume;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            double radius, length, area, volume;

            // get the radius
            radius = Convert.ToDouble(textBox1.Text);

            // calling a delegate
            // construct a delegate
            CalcFigure CF = Get_Length;
            length = CF(radius); // 1. Calling the Get_Length() method

            CF = Get_Area;
            area = CF(radius); // 2. Calling the Get_Area() method

            CF = Get_Volume;
            volume = CF(radius); // 3. Calling the Get_Volume() method

            // output of results
            label2.Text = "Circumference = " + length.ToString();
            label3.Text = "Area of a circle = " + area.ToString();
            label4.Text = "Volume of a sphere = " + volume.ToString();
        }
    }
}

 

4. Run the program

The program window after running is shown in Figure 3.

C#. Windows Forms Application. Executing the program

Figure 3. Executing the program

 


Related topics