Returning Multiple Values

Methods can return only a single value, but this isn’t always convenient. Let’s return to the Time class. It would be great to create a GetTime( ) method to return the hour, minutes, and seconds. You can’t return all three of these as return values, but perhaps you can pass in three parameters, let the GetTime( ) method modify the parameters, and then examine the result in the calling method—in this case, Run( ) . Example 8-3 is a first attempt.

Example 8-3. Retrieving multiple values, first attempt

using System; namespace PassByRef { 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 void DisplayCurrentTime() { System.Console.WriteLine( "{0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second ); } public void GetTime( int theHour, int theMinute, int theSecond ) { theHour = Hour; theMinute = Minute; theSecond )= Second; } // constructor public Time( System.DateTime dt ) { Year = dt.Year; Month = dt.Month; Date = dt.Day; Hour = dt.Hour; Minute = dt.Minute; Second = dt.Second; } } class Tester { public void Run() { System.DateTime currentTime = System.DateTime.Now; Time t = new Time( currentTime ); t.DisplayCurrentTime(); int theHour = 0; int theMinute = 0; int theSecond = 0; t.GetTime( theHour, theMinute, theSecond ); System.Console.WriteLine( "Current time: {0}:{1}:{2}", theHour, theMinute, theSecond ...

Get Learning C# 2005, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.