Wednesday, July 25, 2007

Passing Value-Type Parameters

Passing a value-type variable to a method means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the variable. If you want the called method to change the value of the parameter, you have to pass it by reference, using the ref or out keyword.

Passing Value Types by Value
The following example demonstrates passing value-type parameters by value. The variable myInt 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.
static void SquareIt(int x) { x *= x; }

Passing Value Types by Reference
The following example demonstrates passing value-type parameters by reference using the ref keyword. The value of the parameter is changed after calling the method.
static void SquareIt(ref int x) { x *= x; }

No comments:

Post a Comment