
246
LESSON 20 Reusing Code with Methods
The method takes two parameters, player1 and player2, that are passed by reference. The method
performs some complex calculations not shown here to assign the variables
player1 and player2.
It then returns
true to indicate that it found a match.
The following code shows how a program might call this method:
string playerA = null, playerB = null;
if (GetMatchup(ref playerA, ref playerB))
{
// Announce this match.
...
}
else
{
// No match is possible. We’re done.
...
}
This code declares variables playerA and playerB to hold the selected players’ names. It calls the
method, passing it the two player name variables preceded with the
ref keyword. Depending on
whether the method returns
true or false, the program announces the match or does whatever it
should when all of the matches have been played.
The
out keyword works similarly to the ref keyword except it doesn’t require that the input
variables be initialized. For example, in the preceding example if you don’t initialize
playerA
and
playerB to some value, Visual Studio will warn you that the variables are not initialized and
won’t let you run the program.
In contrast, if you use the
out keyword instead of ref, the values are assumed to be output
parameters from the method, and you are not required to initialize them.
If you use the
out keyword for a parameter, be sure that the method does not tr ...