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

Exercise solution:
Passing struct values as ref parameters


The reference parameter other in DayDifference will be an alternative name of the private instance variable dateOfBirth in a Person object. Thus, the ref parameter other is not a copy of actual parameter. other is an alias of the actual parameter. Thus, the year of dateOfBirth is incremented. We see that this is NOT the same effect as with the call by value parameter on the slide.

In the version on the slide the copy of Date in other is a local copy. It has no effect on the surrounding of DayDifference if we mutate the year of other.

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.