Export (0) Print
Expand All
123 out of 170 rated this helpful - Rate this topic

Passing Parameters

In C#, parameters can be passed either by value or by reference. Passing parameters by reference allows function members (methods, properties, indexers, operators, and constructors) to change the value of the parameters and have that change persist. To pass a parameter by reference, use the ref or out keyword. For simplicity, only the ref keyword is used in the examples of this topic. For information on the difference between ref and out, see ref, out, and Passing Arrays Using ref and out.

This topic includes the following sections:

It also includes the following examples:

Example Demonstrates Uses ref or out
1 Passing value types by value No
2 Passing value types by reference Yes
3 Swapping value types (two integers) Yes
4 Passing reference types by value No
5 Passing reference types by reference Yes
6 Swapping reference types (two strings) Yes

Passing Value-Type Parameters

A value-type variable contains its data directly as opposed to a reference-type variable, which contains a reference to its data. Therefore, 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. For simplicity, the following examples use ref.

Example 1: 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.

// PassingParams1.cs 
using System;
class PassingValByVal
{
    static void SquareIt(int x)
    // The parameter x is passed by value.
    // Changes to x will not affect the original value of myInt.
    {
        x *= x;
        Console.WriteLine("The value inside the method: {0}", x);
    }
    public static void Main()
    {
        int myInt = 5;
        Console.WriteLine("The value before calling the method: {0}",
           myInt);
        SquareIt(myInt);   // Passing myInt by value.
        Console.WriteLine("The value after calling the method: {0}",
           myInt);
    }
}

Output

The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 5

Code Discussion

The variable myInt, being a value type, contains its data (the value 5). When SquareIt is invoked, the contents of myInt are copied into the parameter x, which is squared inside the method. In Main, however, the value of myInt 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.

Example 2: Passing Value Types by Reference

The following example is the same as Example 1, except for passing the parameter using the ref keyword. The value of the parameter is changed after calling the method.

// PassingParams2.cs 
using System;
class PassingValByRef
{
    static void SquareIt(ref int x)
    // The parameter x is passed by reference.
    // Changes to x will affect the original value of myInt.
    {
        x *= x;
        Console.WriteLine("The value inside the method: {0}", x);
    }
    public static void Main()
    {
        int myInt = 5;
        Console.WriteLine("The value before calling the method: {0}",
           myInt);
        SquareIt(ref myInt);   // Passing myInt by reference.
        Console.WriteLine("The value after calling the method: {0}",
           myInt);
    }
}

Output

The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 25

Code Discussion

In this example, it is not the value of myInt that is passed; rather, a reference to myInt is passed. The parameter x is not an int; it is a reference to an int (in this case, a reference to myInt). Therefore, when x is squared inside the method, what actually gets squared is what x refers to: myInt.

Example 3: Swapping Value Types

A common example of changing the values of the passed parameters is the Swap method, where you pass two variables, x and y, and have the method swap their contents. You must pass the parameters to the Swap method by reference; otherwise, you will be dealing with a local copy of the parameters inside the method. The following is an example of the Swap method that uses reference parameters:

static void SwapByRef(ref int x, ref int y)
{
    int temp = x;
    x = y;
    y = temp;
}

When you call this method, use the ref keyword in the call, like this:

SwapByRef (ref i, ref j);

Passing Reference-Type Parameters

A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref (or out) keyword. For simplicity, the following examples use ref.

Example 4: Passing Reference Types by Value

The following example demonstrates passing a reference-type parameter, myArray, by value, to a method, Change. Because the parameter is a reference to myArray, it is possible to change the values of the array elements. However, the attempt to reassign the parameter to a different memory location only works inside the method and does not affect the original variable, myArray.

// PassingParams4.cs 
// Passing an array to a method without the ref keyword.
// Compare the results to those of Example 5.
using System;
class PassingRefByVal 
{
   static void Change(int[] arr)
   {
      arr[0]=888;   // This change affects the original element.
      arr = new int[5] {-3, -1, -2, -3, -4};   // This change is local.
      Console.WriteLine("Inside the method, the first element is: {0}", arr[0]);
   }
   
   public static void Main() 
   {
      int[] myArray = {1,4,5};
      Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", myArray [0]);
      Change(myArray);
      Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", myArray [0]);
   }
}

Output

Inside Main, before calling the method, the first element is: 1
Inside the method, the first element is: -3
Inside Main, after calling the method, the first element is: 888

Code Discussion

In the preceding example, the array, myArray, which is a reference type, is passed to the method without the ref parameter. In such a case, a copy of the reference, which points to myArray, is passed to the method. The output shows that it is possible for the method to change the contents of an array element (from 1 to 888). However, allocating a new portion of memory by using the new operator inside the Change method makes the variable arr reference a new array. Thus, any changes after that will not affect the original array, myArray, which is created inside Main. In fact, two arrays are created in this example, one inside Main and one inside the Change method.

Example 5: Passing Reference Types by Reference

This example is the same as Example 4, except for using the ref keyword in the method header and call. Any changes that take place in the method will affect the original variables in the calling program.

// PassingParams5.cs 
// Passing an array to a method with the ref keyword.
// Compare the results to those of Example 4.
using System;
class PassingRefByRef 
{
   static void Change(ref int[] arr)
   {
      // Both of the following changes will affect the original variables:
      arr[0]=888;
      arr = new int[5] {-3, -1, -2, -3, -4};
      Console.WriteLine("Inside the method, the first element is: {0}", arr[0]);
   }
   
   public static void Main() 
   {
      int[] myArray = {1,4,5};
      Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", myArray [0]);
      Change(ref myArray);
      Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", myArray [0]);
   }
}

Output

Inside Main, before calling the method, the first element is: 1
Inside the method, the first element is: -3
Inside Main, after calling the method, the first element is: -3

Code Discussion

All of the changes that take place inside the method affect the original array in Main. In fact, the original array is reallocated using the new operator. Thus, after calling the Change method, any reference to myArray points to the five-element array, which is created in the Change method.

Example 6: Swapping Two Strings

Swapping strings is a good example of passing reference-type parameters by reference. In the example, two strings, str1 and str2, are initialized in Main and passed to the SwapStrings method as parameters modified by the ref keyword. The two strings are swapped inside the method and inside Main as well.

// PassingParams6.cs
using System;
class SwappinStrings
{
    static void SwapStrings(ref string s1, ref string s2)
    // The string parameter x is passed by reference.
    // Any changes on parameters will affect the original variables.
    {
        string temp = s1;
        s1 = s2;
        s2 = temp;
        Console.WriteLine("Inside the method: {0}, {1}", s1, s2);
    }
    public static void Main()
    {
        string str1 = "John";
        string str2 = "Smith";
        Console.WriteLine("Inside Main, before swapping: {0} {1}", 
           str1, str2);
        SwapStrings(ref str1, ref str2);   // Passing strings by reference
        Console.WriteLine("Inside Main, after swapping: {0}, {1}", 
           str1, str2);
    }
}

Output

Inside Main, before swapping: John Smith
Inside the method: Smith, John
Inside Main, after swapping: Smith, John

Code Discussion

In this example, the parameters need to be passed by reference to affect the variables in the calling program. If you remove the ref keyword from both the method header and the method call, no changes will take place in the calling program.

For more information on strings, see the string keyword.

See Also

Passing Arrays Using ref and out | C# Language Features

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.