Returning Objects

Because C# is a garbage collecting language, it is much more common for objects to be returned by methods. When an object of class type is returned, reference counting is used to track the returned object. This makes it feasible to design code differently from C++ code, because in C++ the delete operator must be applied to free dynamically allocated storage.

Due to the fact that arrays are implemented as objects, it is possible to return array types from methods. This is not possible in C++. The next example contains a method that returns an array.

// Factors - Returns an array object from a method

using System;

class Program
    static void Main()
        uint[] f = Factors(1000u);
        Console.WriteLine("Factors of 1000 are: ");

        for (int i=0; i < f.Length; i++)

    static uint[] Factors(uint n)
        if (n == 0) return new uint[0];
        if (n == 1) return new uint[1] { 1 };

        uint count = 2;
        for (uint i = 2; i < n; i++)
            if (n % i == 0) count++;

        uint[] factors = new uint[count];

        for (uint i = 1, j = 0; i <= n; i++)
            if (n % i == 0)
                factors[j++] = i;

        return factors;

The output of the program is shown below.

Factors of 1000 are: 

The method Factors checks two special cases, the input number is zero and the input number is one. If the input number is zero, an empty array is returned (indicating no factors). If the input number is one, an array containing only one is returned. Every other number has at least two factors, one and itself; although, clearly it may have more. An initial pass is made to determine the size of the array required to hold the factors. Once this information has been ascertained, the array is allocated and populated with the factors of the given number.

It is really quite nice to consider that the above program embodies a new technique. The programmer does not have to be concerned about the destruction of the returned object because the reference counting engine handles its lifetime. This opens up many possibilities with respect to programming.