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 9-3 is a first attempt.

Example 9-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;

        // Property (read only)
        public int GetHour()
        {
            return Hour;
        }

        // 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 h, int m, int s)
                       {
                           h = Hour;
                           m = Minute;
                           s = 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, ...

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.