Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Passing references as ref parameters


The C# ref parameter other in the method DayDifference will be an alternative name of the private instance variable dateOfBirth in an object of class Person. The year of this date of birth is incremented. This is the same effect as with the call-by-value parameter.

If the parameter other is a ref parameter it is important to notice what happens, if we assign to this parameter. We do not, however, in the concrete program. If we did, we could arrange that the private instance variable dateOfBirth in the Person object becomes a reference to a new Date.

Here is a tabular overview of the two exercises and the programs on the corresponding slides:

class struct
by value Like call by reference in C. The parameter other is a reference to another date. We can mutate this date, but we cannot change the value of the actual parameter dateOfBirth by assigning to other.

The birthday can be mutated.

A struct dateOfBirth is copied to other. The year of the copied Date is changed. It does not affect the dateOfBirth. This is pure value semantics. Value types (structs) and call by value fit nicely together.

The birthday is protected from mutation.

by C# ref The formal parameter other becomes an alias of the actual parameter dateOfBirth. We can therefore mutate this date, as above. If we assign to other we do, in reality, assign to dateOfBirth. This observation is the real difference between this case and the case above.

The birthday can be mutated.

As above, the formal parameter other becomes an alias of the actual parameter dateOfBirth. If we mutate the year of other, we change the year of dateOfBirth. If we assign to other we will (by copying and value semantics) change the dateOfBirth.

The birthday can be mutated.