Handling Methods and Functions
(Page 1 of 5 )
In this conclusion to a four-part series on classes and objects in C#, you'll learn how to overload methods and constructors, handle property class modifiers, and more. This article is excerpted from chapter four of the book
Programming C# 3.0, fifth edition, written by Jesse Liberty and Donald Xie (O'Reilly, 2008; ISBN: 0596527438). Copyright © 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Overcoming Definite Assignment without Parameters
C# imposes definite assignment, which requires that all variables be assigned a value before they are used. In Example 4-7, if you don’t initializetheHour,theMinute, andtheSecondbefore you pass them as parameters toGetTime(), the compiler will complain. Yet, the initialization that is done merely sets their values to0before they are passed to the method:
int theHour = 0;
int theMinute = 0;
int theSecond = 0;
t.GetTime( ref theHour, ref theMinute, ref theSecond);
It seems silly to initialize these values because you immediately pass them by reference intoGetTime where they’ll be changed, but if you don’t, the following compiler errors are reported:
Use of unassigned local variable
'theHour'
Use of unassigned local variable 'theMinute'
Use of unassigned local variable 'theSecond'
C# provides theoutparameter modifier for this situation. Theoutmodifier removes the requirement that a reference parameter be initialized. The parameters toGetTime(), for example, provide no information to the method; they are simply a mechanism for getting information out of it. Thus, by marking all three asoutparameters, you eliminate the need to initialize them outside the method. Within the called method, theoutparameters must be assigned a value before the method returns. The following are the altered parameter declarations forGetTime():
public void GetTime(out int h, out int m, out int s)
{
h = Hour;
m = Minute;
s = Second;
}
And here is the new invocation of the method inMain():
t.GetTime( out theHour, out theMinute, out theSecond);
To summarize, value types are passed into methods by value.refparameters are used to pass value types into a method by reference. This allows you to retrieve their modified values in the calling method.outparameters are used only to return information from a method. Example 4-8 rewrites Example 4-7 to use all three.
Example 4-8. Using in, out, and ref parameters
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace InOutRef
{
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 int GetHour()
{
return Hour;
}
public void SetTime( int hr, out int min, ref int sec )
{
// if the passed in time is >= 30
// increment the minute and set second to 0
// otherwise leave both alone
if ( sec >= 30 )
{
Minute++;
Second = 0;
}
Hour = hr; // set to value passed in
// pass the minute and second back out
min = Minute;
sec = 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;
}
}
public class Tester
{
static void Main()
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time( currentTime );
t.DisplayCurrentTime();
int theHour = 3;
int theMinute;
int theSecond = 20;
t.SetTime( theHour, out theMinute, ref theSecond );
System.Console.WriteLine(
"the Minute is now: {0} and {1} seconds",
theMinute, theSecond );
theSecond = 40;
t.SetTime( theHour, out theMinute, ref theSecond );
System.Console.WriteLine( "the Minute is now: " +
"{0} and {1} seconds", theMinute, theSecond );
}
}
}
Output:
11/17/2007 14:6:24
the Minute is now: 6 and 24 seconds
the Minute is now: 7 and 0 seconds
SetTimeis a bit contrived, but it illustrates the three types of parameters.theHouris passed in as a value parameter; its entire job is to set the member variableHour, and no value is returned using this parameter.
TherefparametertheSecondis used to set a value in the method. IftheSecondis greater than or equal to 30, the member variableSecond is reset to 0, and the member variableMinuteis incremented.
You must specifyrefon the call and the destination when using reference parameters.
Finally,theMinuteis passed into the method only to return the value of the member variableMinute, and thus is marked as anoutparameter.
It makes perfect sense thattheHourandtheSecondmust be initialized; their values are needed and used. It is not necessary to initializetheMinute, as it is anoutparameter that exists only to return a value. What at first appeared to be arbitrary and capricious rules now make sense; values are required to be initialized only when their initial value is meaningful.
Next: Overloading Methods and Constructors >>
More C# Articles
More By O'Reilly Media