O'Reilly logo

Learning C# by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required