Passing Value-Type Parameters
The following example demonstrates passing value-type parameters by value. The variable n is passed by value to the method SquareIt. Any changes that take place inside the method have no affect on the original value of the variable.
class PassingValByVal
{
static void SquareIt(int x)
// The parameter x is passed by value.
// Changes to x will not affect the original value of x.
{
x *= x;
System.Console.WriteLine(x);
}
static void Main()
{
int n = 5;
System.Console.WriteLine(n);
SquareIt(n); // Passing the variable by value.
System.Console.WriteLine(n);
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 5
*/
The variable n, being a value type, contains its data, the value 5. When SquareIt is invoked, the contents of n are copied into the parameter x, which is squared inside the method. In Main, however, the value of n is the same, before and after calling the SquareIt method. In fact, the change that takes place inside the method only affects the local variable x.
The following example is the same as the previous example, except for passing the parameter using the ref keyword. The value of the parameter is changed after calling the method.
{
static void SquareIt(ref int x)
// The parameter x is passed by reference.
// Changes to x will affect the original value of x.
{
x *= x;
System.Console.WriteLine(x);
}
static void Main()
{
int n = 5;
System.Console.WriteLine(n);
SquareIt(ref n); // Passing the variable by reference.
System.Console.WriteLine(n);
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 25
*/
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home