Passing By Reference To Methods


The examples to date have passed value types as parameters. The next example shows how a reference may also be passed to a method.

// Point5 - Passing References

using System;

class Point
{
    public double x;
    public double y;

    public Point()
    {
        x = 0;
        y = 0;
    }

    public Point(double xSet, double ySet)
    {
        x = xSet;
        y = ySet;
    }

    public Point(Point copy) // Pass a Reference Here
    {
        x = copy.x;
        y = copy.y;
    }

    public void CopyDouble(Point copy) // Reference Passed Here
    {
        copy.x *= 2;                   // Update Original Object
        copy.y *= 2;
        x = copy.x;                    // Then Copy Updated Object
        y = copy.y;
    }

    public void Write()
    {
        Console.WriteLine("Point(" + x + "," + y + ")");
    }
}

class PointDemo
{
    static void Main()
    {
        Point p = new Point(3, 4);
        p.Write();

        Point q = new Point(p);
        q.Write();

        Point r = new Point();
        r.CopyDouble(p);

        r.Write();
        p.Write();
    }
}

The output of the program is shown below.

Point(3,4)
Point(3,4)
Point(6,8)
Point(6,8)

The copy constructor receives a reference to a point. It copies the coordinates of the point to the current instance. The method CopyDouble does something interesting. Not only does it receive a reference to a point, it changes that which is referred to (then copies it). The second last print line Point(6,8) is the result of the copied point. However, notice that the last print line (also Point(6,8)) is the updated point p. That is, when an object is passed by reference, it is open to being updated in the called procedure. Despite this, assigning a new value to the parameter (copy in this case) has no effect on the original reference. That is, the reference itself is passed by value and the original reference always remains unaffected.

The method CopyDouble shows how references and values behave somewhat differently when being passed as parameters. When a value type is passed as a parameter, it is copied, and changes to the copy inside the called procedure have no impact on the original value. When a reference is passed, changes to the object being referenced are reflected in the original object.

Reiterating, when a variable of a class type is created, a reference to the object is created. When such a reference is passed to a method, the parameter that receives it refers to the same object as that referred to by the argument. This means that objects are passed to methods as call-by-reference. Therefore changes to the passed object affect the object used as an argument.

C# has a number of facilities for adjusting how both references and values are passed. These are discussed in the sections that follow.