C#. The constituent elements of the class. Constant fields in classes. Keywords readonly, const

The constituent elements of the class. Constant fields in classes. Keywords readonly, const


Contents


1. What constituent elements can a class include in C#?

Class may include the following constituent elements:

  • fields (data);
  • constructors;
  • methods;
  • overloaded operators;
  • properties;
  • events;
  • nested classes.

 

2. What keywords can be used when declaring fields (data) of a class?

When declaring fields, the following keywords may be used:

  • static. This keyword is used to declare a static data field. More details about using static fields and methods is described here;
  • const – used to declare a constant field. The value of such a field cannot be changed;
  • readonly – used to declare a read-only field. It is allowed to set the readonly field value in the class constructor only once.

 

3. Features of using const modifier for class fields. General form

The const modifier defines a field that cannot be changed (constant field). Features of using a constant field in a class are as follows:

  • when declaring, the field with const modifier must necessarily be initialized to some value;
  • constant fields are considered static, therefore, access to such fields from the outside should be as for static ones using the class name (and not the instance name).

The general form of declaring a field with a const modifier is:

access_modifier const type const_name = value;

where

  • access_modifier – one of five access modifiers (private, protected, public, internal, protected internal);
  • type – the type of the class field, which is declared as a constant;
  • const_name – the name of the field;
  • value – a constant value that must be compatible with type.


 

4. An example of using the const modifier for a class field

In the example, the CircleFigures class is declared, which implements methods for calculating the characteristics of geometric figures that are constructed using a circle.

Class contains the following elements:

  • the public constant Pi, which is declared with the const keyword;
  • method Length(), which determines the circumference of a given radius;
  • method Area(), which determines the circumference of a circle of a given radius;
  • method Volume(), which determines the volume of a sphere of a given radius.

The main() function implements instantiation and calling class methods. Also demonstrated access to the constant field Pi, which is implicitly considered static.

using System;
using static System.Console;

namespace ConsoleApp2
{
  // A class that implements the calculation of the area of various figures
  class CircleFigures
  {
    // constant field - cannot be changed in the class
    public const double Pi = 3.141592; // implicitly considered static

    // method that calculates the circumference of a given radius
    public double Length(double radius)
    {
      // used internal constant Pi
      return 2 * Pi * radius;
    }

    // method for calculating the circumference of a given radius
    public double Area(double radius)
    {
      // used internal constant Pi
      return Pi * radius * radius;
    }

    // method calculating the volume of a sphere of a given radius
    public double Volume(double radius)
    {
      // used internal constant Pi
      return 4.0 / 3 * Pi * radius * radius * radius;
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      // Using constants in classes, the const keyword
      // 1. Create an instance of class CircleFigures
      CircleFigures cf = new CircleFigures();

      // 2. Calculate circumference of radius 1
      double length = cf.Length(1.0);
      // output accuracy - 2 decimal places
      WriteLine("length = {0:f2}", length);

      // 3. Calculate the area of a circle of radius 2
      double area = cf.Area(2.0);
      WriteLine("area = {0:f2}", area);

      // 4. Calculate the volume of a sphere of radius 3
      double volume;
      volume = cf.Volume(3.0);
      WriteLine("volume = {0:f2}", volume);

      // 5. Calling constant field Pi - class name is used
      WriteLine("Pi = {0}", CircleFigures.Pi);
    }
  }
}

The result of the program

length = 6.28
area = 12.57
volume = 113.10
Pi = 3.141592

In the above code, when trying to change the value of the constant Pi in the class methods, an error will be generated at the compilation stage

The left-hand side of an assignment must be a variable, property or indexer

 

5. Features of using readonly modifier for class fields. General form

A field can be declared with readonly modifier. The value of such a field can be initialized in one of two ways:

  • in the class constructor;
  • immediately when declaring.

The general form for declaring a readonly field is as follows:

access_modifier readonly type var_name = value;

where

  • access_modifier – one of five access modifiers (private, protected, public, internal, protected internal);
  • type – type of the declared field of the class;
  • var_name – the name of the field;
  • value – the value by which the field is initialized. The value may be assigned only once. The value must be compatible with type.

 

6. An example of using the readonly modifier in a class

The example demonstrates the use of the readonly modifier in a class that implements a fixed-size array.

The class MyArrayFixed is declared in which the following are implemented:

  • internal integer variable Count, declared with readonly modifier. This variable determines the number of elements in the array, which is fixed. The value of this variable is set to 5 by default. In any class constructor, you can change this value only once. In other methods of the class, it is impossible to change the value of the Count variable;
  • the internal variable DefaultValue of type double, which is declared with the readonly modifier. The variable defines the value of the elements of the array, which are assigned to it by default. The rules for using this variable are the same as for the Count variable;
  • constructor MyArrayFixed()with two parameters. This constructor once generates the value of the readonly fields of the class. Also, in the constructor the memory for the Array array is allocated, also the value of the items is set to DefaultValue;
  • constructor MyArrayFixed() with one parameter. This constructor is redirected to another constructor with two parameters;
  • demo method SetDefaultValue(), in which an attempt to change the value of the readonly field DefaultValue is commented out. If you remove the comment in the line, the compiler will generate an error.

The example text for an application such as Console Application is as follows:

using System;
using static System.Console;

namespace ConsoleApp2
{
  // A class that implements an array in which the number of elements is determined by a given range
  class MyArrayFixed
  {
    // declaration of fields with readonly modifier
    public readonly int Count = 5; // The current number of items in the array is 5
    public readonly double DefaultValue; // value of the items of the array by default
    public double[] Array = null;

    // Initialization of fields in the class constructor - only once
    public MyArrayFixed(int _Count, double _DefaultValue)
    {
      // 1. Initialize readonly fields of the class
      // The array must have at least 5 items
      if (_Count > Count)
        Count = _Count;

      // it is possible to initialize readonly fields several times but only in the constructor
      DefaultValue = 0.0;
      DefaultValue = _DefaultValue;

      // 2. Allocate memory for the array
      Array = new double[Count];

      // 3. Fill array with DefaultValue values
      for (int i = 0; i < Array.Length; i++)
        Array[i] = DefaultValue;
    }

    // Constructor with 1 parameter
    public MyArrayFixed(int _Count) : this(_Count, 0.0)
    {

    }

    // You cannot set a value again in class methods
    void SetDefaultValue()
    {
      // DefaultValue = 2.5; - the compiler error
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      // Using readonly fields in classes
      // 1. Create an object of MyArrayFixed class
      MyArrayFixed af = new MyArrayFixed(7, 3.5);

      // 2. Output the array to the screen and its readonly fields
      WriteLine("Array af.");
      WriteLine($"af.Count = {af.Count}");
      WriteLine("af.DefaultValue = {0}", af.DefaultValue);
      WriteLine("Items of array:");

      for (int i = 0; i < af.Array.Length; i++)
      {
        Write("{0}\t", af.Array[i]);
      }
      WriteLine();
    }
  }
}

The result of the program

Array af.
af.Count = 7
af.DefaultValue = 3.5
Items of array:
3.5 3.5 3.5 3.5 3.5 3.5 3.5

 


Related topics