C#. An example of solving problems using static data and methods in a class

An example of solving problems using static data and methods in a class

This example implements the solution of tasks using static data and methods. In this example, you can learn how to develop your own classes that contain static data and methods.


Contents


The task

Task 1. Given the class Point, which defines a point on the coordinate plane. Implement a count of the number of created instances of type Point. The Point class is declared as non-static.

Task 2. Modify the Point class as follows:

  • add a static LengthPoints() method to calculate the distance between two points. The method should receive instances of type Point as parameters.

In the main() function, demonstrate the call to the static LengthPoints() method.

 

Considerations

To count the number of instances of type Point, you need to create a static field (data element) count. Then, in the static constructor, initialize this field with the value 0. When creating a new instance of the Point class, the static field count should increase by 1. This means that the count++ increment code needs to be placed in non-static Point class constructors.

 

Task 1. Solution

The solution to the problem is implemented in a C# application created using the Console Application template. The following elements are implemented in the Point class:

  • internal (private) variables x, y, which determine the coordinates of the point;
  • static variable count, which is used to count the number of created instances of the class;
  • non-static constructor Point(double, double) with two parameters that initialize the class’s internal fields of the same name;
  • non-static Point() constructor without parameters, which initializes the internal fields of the class with a value of 1.0;
  • the static constructor Point(), which initializes the static variable count to zero;
  • access methods to internal variables x, y with the names GetX(), GetY(), SetX(), SetY();
  • Print() method – implemented to display the internal fields of the class.

The main() function demonstrates the use of an instance of the Point class and counts the number of created instances of this class.
The text of the program is as follows.

using System;
using static System.Console; // Include static class System.Console

namespace ConsoleApp2
{
  // Topic: Static data and methods

  // Non-static class Point
  class Point
  {
    // 1. Internal fields of class Point
    // point coordinates
    private double x;
    private double y;

    // number of instances of class Point - static field
    // if you remove public, then the field will be visible only within the class
    public static int count;

    // 2. Static constructor
    // - initializes only static fields of a class
    // - cannot have parameters and access modifiers
    // - performed only once
    // - called by .NET environment
    static Point()
    {
      count = 0;
      // x = y = 0; - error, non-static class fields cannot be initialized in the static constructor
    }

    // 3. Non-static constructor - initializes non-static class fields
    public Point()
    {
      x = y = 1.0;

      // The constructor is called when instantiating the Point class,
      // therefore you need to increase the static field by 1
      count++;
    }

    // 4. Another non-static constructor with two parameters
    public Point (double x, double y)
    {
      this.x = x;
      this.y = y;

      // The constructor is called when instantiating the Point class,
      // therefore you need to increase the static field by 1
      Point.count++; // another way to access count
    }

    // 5. Access methods
    public double GetX() { return x; }
    public double GetY() { return y; }
    public void SetX(double x) { this.x = x; }
    public void Set(double y) { this.y = y; }

    // 6. Method that outputs class fields
    public void Print()
    {
      WriteLine("Fields of instance: ");
      WriteLine("x = {0}, y = {1}", x, y);
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      // 1. Declare multiple instances of a class
      Point pt1 = new Point(); // a single instance
      Point pt2 = new Point(2, 3.5);

      // 2. Print the instances of the class
      Write("Object pt1. ");
      pt1.Print();
      Write("Object pt2. ");
      pt2.Print();

      // 3. Print the static field Point.count
      WriteLine($"Static field Point.count = {Point.count}"); // count = 2

      // 4. Declare an array of instances
      Point[] ptArray = new Point[5]; // create an array of references to Point

      // 5. Print out the static field Point.count again
      WriteLine($"Static field Point.count = {Point.count}"); // count = 2

      // 6. Allocate memory for each element of an array of type Point
      for (int i=0; i<ptArray.Length; i++)
      {
        // every time the constructor is called,
        // the static field count is increased by 1
        ptArray[i] = new Point(i, i * i);
      }

      // 7. Print the value Point.count - the number of class instances created.
      WriteLine($"Static field Point.count = {Point.count}"); // count = 7
    }
  }
}


 

Task 2. Solution

To perform task 2, you need to add the code of the static method LengthPoints() to the text of the class Point, the listing of which is as follows

...

// Non-static class Point
class Point
{

  // the previous code remains unchanged
  // ...

  // 7. Static Method LengthPoints() - calculates the distance between two points of type Point
  public static double LengthPoints(Point p1, Point p2)
  {
    double len;
    len = Math.Sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
    return len;
  }
}

...

To demonstrate the LengthPoints() method, add the appropriate call code to the text of the main() function:

static void Main(string[] args)
{

  // the previous code remains unchanged
  // ...

  // 8. Demonstration of a call to the static method LengthPoints()
  WriteLine("Length between pt1 and pt2 is: {0:f3}", Point.LengthPoints(pt1, pt2));
}

The result of the program

Object pt1. Fields of instance:
x = 1, y = 1
Object pt2. Fields of instance:
x = 2, y = 3.5
Static field Point.count = 2
Static field Point.count = 2
Static field Point.count = 7

 


Related topics