CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
Numerical data falls under the category of value types. Therefore, if you change the values of the
parameters within the scope of the member, the caller is blissfully unaware, given that you are changing
the values on a copy of the caller’s original data:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****\n");
// Pass two variables in by value.
int x = 9, y = 10;
Console.WriteLine("Before call: X: {0}, Y: {1}", x, y);
Console.WriteLine("Answer is: {0}", Add(x, y));
Console.WriteLine("After call: X: {0}, Y: {1}", x, y);
Console.ReadLine();
}
As you would hope, the values of x and y remain identical before and after the call to Add(), as
shown in the following output, as the data points were sent in by value. Thus, any changes on these
parameters within the Add() method are not seen by the caller, as the Add() method is operating on a
copy of the data.
***** Fun with Methods *****
Before call: X: 9, Y: 10
Answer is: 19
After call: X: 9, Y: 10
The out Modifier
Next, you have the use of output parameters. Methods that have been defined to take output parameters
(via the out keyword) are under obligation to assign them to an appropriate value before exiting the
method scope (if you fail to do so, you will receive compiler errors).
To illustrate, here is an alternative version of the Add() method that returns the sum of two integers
using the C# out modifier (note the physical return value of this method is now void):
// Output parameters must be assigned by the called method.
static void Add(int x, int y, out int ans)
{
ans = x + y;
}
Calling a method with output parameters also requires the use of the out modifier. However, the
local variables that are passed as output variables are not required to be assigned before passing them in
as output arguments (if you do so, the original value is lost after the call). The reason the compiler allows
you to send in seemingly unassigned data is due to the fact that the method being called must make an
assignment. The following code is an example:
123