C#. Passing in the function one-dimensional and multidimensional arrays of class instances as ref- and out-parameters




Passing in the function one-dimensional and multidimensional arrays of class instances as ref and out parameters


Contents


Search other websites:

1. Features of passing references to arrays of class instances using ref and out modifiers

There are 2 ways to pass references to arrays of class instances to a function:

  • passing parameter by value. In this case, the array is completely copied to the function. Changing the values of an array inside a function will not change these values in the calling code;
  • passing parameter by reference. In this case, ref or out modifiers are used. When passing a value by reference, you can change the number of items in the array, reallocate memory for each item, and fill these items of the array with new values.

So, when passing an array with ref or out modifiers:

  • You can change the value of the reference itself. This means that you can reallocate memory for the array and its items and fill in the array items with new values;
  • the change in the values of the array elements inside the function will be displayed in the calling code.

 

2. Passing a one-dimensional array of type int as a ref parameter. Example

The following example develops an Integer class that contains one internal value parameter.

The following items are declared in the tested class Program:

  • static function GetArray(), forming an array of random numbers of type Integer. The function receives as input parameter an array A of type Integer[] as a ref parameter and reallocates memory for the reference A. The function reallocates memory for any instance and fills the instance fields with values. Changing values is fixed in the calling function main();
  • static function SumIntegers() – designed to calculate the sum of the integer values of an array of type Integer. The function receives an array of type Integer[] as a ref-reference.

After the program terminates, there is no need to free memory (as in C++). The memory will be freed automatically during the so-called “garbage collection”.

using System;

namespace ConsoleApp2
{
  // Class Integer - reference type
  class Integer
  {
    public int value;
  }

  class Program
  {
    // Static function GetArray() forms an array of random numbers,
    // the array is passed as a ref parameter, you can change A itself
    static void GetArray(ref Integer[] A)
    {
      // 1. Initialize random number generator
      Random rnd_num = new Random();

      // 2. Change the number of items in array A - reallocate memory
      // the reference itself changes - allocate memory for 6 instances
      A = new Integer[6];

      // 3. Allocate memory for each instance separately
      for (int i = 0; i < A.Length; i++)
      {
        A[i] = new Integer();
      }

      // 4. Fill the array with random integers within [0; 10]
      for (int i = 0; i < A.Length; i++)
      {
        // All variables in the array will be displayed outside this function.
        A[i].value = rnd_num.Next(0, 10);
      }

      // 5. Return from function
      return;
    }

    // A static function that calculates the sum of the items of array,
    // array is passed by reference (with ref modifier)
    static int SumIntegers(ref Integer[] A)
    {
      int sum = 0;
      for (int i=0; i<A.Length; i++)
      {
        sum += A[i].value;
      }
      return sum;
    }

    static void Main(string[] args)
    {
      // Passing a ref-array of class instances to a method

      // 1. Declare the array of type Integer
      const int MAX_ITEMS = 8; // maximum number of items in the array
      Integer[] Array;

      // 2. Allocate memory for MAX_ITEMS items
      Array = new Integer[MAX_ITEMS];

      // 3. Allocate memory for each item of type Integer
      for (int i = 0; i < Array.Length; i++)
        Array[i] = new Integer();

      // 4. Fill Array with values from 1 to Array.Length
      for (int i=0; i<Array.Length; i++)
      {
        Array[i].value = i + 1;
      }

      // 5. Print the array to a string on the screen
      Console.WriteLine("Items in Array:");
      for (int i=0; i<Array.Length; i++)
      {
        Console.Write($"{Array[i].value}\t");
      }

      // 6. Fill Array with random numbers
      // by calling the GetArray() function
      GetArray(ref Array); // static function, modifies the array internally

      // 7. Display the changed array on the screen
      Console.WriteLine("\nArray after random forming:");
      for (int i=0; i<Array.Length; i++)
      {
        Console.Write($"{Array[i].value}\t");
      }

      // 8. Calculate the sum of the items of the changed array and display it on the screen
      int summ = Program.SumIntegers(ref Array);
      Console.WriteLine($"\nsumm = {summ}");
    }
  }
}

The result of the program:

Items in Array:
1 2 3 4 5 6 7 8
Array after random forming:
4 3 8 9 7 7
summ = 38


 

3. Passing a one-dimensional array of class instances as an out-parameter. Example

This example is very close to the example in paragraph 2 (passing an array as a ref parameter). The only difference is in the GetArray() function, in which the ref modifier is replaced with the out modifier.

using System;

namespace ConsoleApp2
{
  // Class Integer - reference type
  class Integer
  {
    public int value;
  }

  class Program
  {
    // The static function GetArray() generates forms an array of random numbers,
    // array is passed as out-parameter, you can change the reference A itself
    static void GetArrayOut(out Integer[] A)
    {
      // 1. Initialize random number generator
      Random rnd_num = new Random();

      // 2. Change the number of items in array A
      A = new Integer[6]; // the reference itself changes - allocate memory for 6 instances

      // 3. Allocate memory for each instance separately
      for (int i = 0; i < A.Length; i++)
      {
        A[i] = new Integer();
      }

      // 4. Fill the array with random integers within [0; 10]
      for (int i = 0; i < A.Length; i++)
      {
        // All changes in the array will be displayed outside this function.
        A[i].value = rnd_num.Next(0, 10);
      }

      // 5. Return from function
      return;
    }

    // A static function that calculated the sum of the items of the array,
    // array is passed by reference (with the ref modifier)
    static int SumIntegers(ref Integer[] A)
    {
      int sum = 0;
      for (int i=0; i<A.Length; i++)
      {
        sum += A[i].value;
      }
      return sum;
    }

    static void Main(string[] args)
    {
      // Passing an out-array of class instances to a method

      // 1. Declare an array of type Integer
      const int MAX_ITEMS = 8; // maximum number of items in the array
      Integer[] Array;

      // 2. Allocate memory for MAX_ITEMS items
      Array = new Integer[MAX_ITEMS];

      // 3. Allocate memory for each item of type Integer
      for (int i = 0; i < Array.Length; i++)
        Array[i] = new Integer();

      // 4. Fill Array with fixed values from 1 to MAX_ITEMS
      for (int i=0; i<Array.Length; i++)
      {
        Array[i].value = i + 1;
      }

      // 5. Print the array to screen
      Console.WriteLine("Items in Array:");
      for (int i=0; i<Array.Length; i++)
      {
        Console.Write($"{Array[i].value}\t");
      }

      // 6. Fill Array with random numbers
      // by calling the GetArray() function
      GetArrayOut(out Array); // static function, modifies the array internally

      // 7. Display the changed array on the screen
      Console.WriteLine("\nArray after random forming:");
      for (int i=0; i<Array.Length; i++)
      {
        Console.Write($"{Array[i].value}\t");
      }

      // 8. Calculate the sum of the items of the changed array and display it on the screen
      int summ = Program.SumIntegers(ref Array);
      Console.WriteLine($"\nsumm = {summ}");
    }
  }
}

The result of the program:

Items in Array:
1 2 3 4 5 6 7 8
Array after random forming:
1 4 5 9 5 2
summ = 26

 

4. Passing a two-dimensional array of class instances as a ref-parameter. Example

The example demonstrates passing a two-dimensional array of class instances as a ref-parameter to a function. If it is necessary to implement the passing a two-dimensional array to the function as an out-parameter, then the ref modifier is replaced by the out modifier.

The program implements the following classes and methods:

  • class Integer – implements an integer;
  • the static method GetArray2D(), which receives the parameters a reference to a two-dimensional array A of instances of the class Integer and a reference to the variables Rows, Columns (number of rows and number of columns). In this method, memory is allocated for the array, the sizes and value of its elements are formed. All changes inside the function will be displayed in the calling code (main() function);
  • static method SumIntegers2D(), which receives as parameters ref-reference to the array and its dimension. The method calculates the sum of the items of the array;
  • static method PrintArray2D(), which receives the array and its dimension by value (without ref or out modifiers). This method displays the array on the screen.

The program code is as follows

using System;

namespace ConsoleApp2
{
  // Class Integer - reference type
  class Integer
  {
    public int value;
  }

  class Program
  {
    // The static function GetArray2D() generates an array of random numbers.
    // The array is passed as a ref parameter, you can change the reference A.
    // Parameters Rows, Columns return the number of columns and rows of the array.
    static void GetArray2D(ref Integer[,] A, ref int Rows, ref int Columns)
    {
      // 1. Initialize random number generator
      Random rnd_num = new Random();

      // 2. Form the size of array
      Rows = 3;
      Columns = 4;

      // 3. Allocate memory for a two-dimensional array
      A = new Integer[Rows, Columns];

      // 4. Allocate memory for each instance separately
      for (int i = 0; i < Rows; i++)
        for (int j = 0; j < Columns; j++)
        {
          A[i, j] = new Integer();
        }

      // 5. Fill the array with random integers within [0; 10]
      for (int i = 0; i < Rows; i++)
        for (int j = 0; j < Columns; j++)
        {
          // All changes in the array will be displayed outside this function.
          A[i, j].value = rnd_num.Next(0, 10);
        }

      // 6. Return from function
      return;
    }

    // A static function that calculates the sum of the items of a two-dimensional array.
    // The array is passed by reference (with the ref modifier).
    // Parameters Rows, Columns are passed by value.
    static int SumIntegers2D(ref Integer[,] A, int Rows, int Columns)
    {
      int sum = 0;
      for (int i = 0; i < Rows; i++)
        for (int j = 0; j < Columns; j++)
        {
          sum += A[i, j].value;
        }
      return sum;
    }

    // The static function PringArray2D (), which displays a two-dimensional array on the screen.
    // The function receives an array A, the sizes of the array m, n.
    // Parameters are passed by value
    static void PrintArray2D(Integer[,] A, int m, int n)
    {
      for (int i = 0; i < m; i++)
      {
        for (int j = 0; j < n; j++)
        {
          Console.Write("{0}\t", A[i, j].value);
        }
        Console.WriteLine();
      }
    }

    static void Main(string[] args)
    {
      // Passing a two-dimensional ref array of class instances to a method

      // 1. Declare a reference to a two-dimensional array of type Integer
      Integer[,] Array2D = null;

      // 2. Set the number of rows and columns in the array
      int m, n;
      m = 2;
      n = 3;

      // 3. Form the array using the GetArray2D() function
      GetArray2D(ref Array2D, ref m, ref n);

      // 4. Display the generated array on the screen
      Console.WriteLine("Array2D:");
      PrintArray2D(Array2D, m, n);

      // 5. Calculate the sum of the items of the array and display it on the screen.
      int summ = SumIntegers2D(ref Array2D, m, n);
      Console.WriteLine($"summ = {summ}");
    }
  }
}

The result of the program

Array2D:
5 1 7 6
7 7 8 9
7 2 3 7
summ = 69

 


Related topics