Passing Parameters
By default, value types are passed into methods by value. (See the section "Method Arguments" earlier in this chapter.) This means that when a value object is passed to a method, a temporary copy of the object is created within that method. Once the method completes, the copy is discarded. Although passing by value is the normal case, there are times when you will want to pass value objects by reference. C# provides the ref parameter modifier for passing value objects into a method by reference, and the out modifier for those cases in which you want to pass in a variable by reference without first initializing it.
C# also supports the params modifier, which allows a method to accept a variable number of parameters. We discuss the params keyword in Chapter 9.
Passing by Reference
Methods can return only a single value (though that value can itself be a collection of values). Let's return to the Time class and add a GetTime( ) method, which returns the hour, minutes, and seconds.
Because you can't return three values, perhaps you can pass in three parameters, let the method modify the parameters, and examine the result in the calling method. Example 4-8 shows a first attempt at this.
Example 4-8. Returning values in parameters
using System; namespace ReturningValuesInParams { public class Time { // private member variables private int Year; private int Month; private int Date; private int Hour; private int Minute; private int Second; // public accessor methods public ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access