Click to Rate and Give Feedback
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
C# Programming Guide
Passing Parameters (C# Programming Guide)

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

The following example illustrates the difference between value and reference parameters.

C#
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16 
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }

    // Passing by reference
    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}

For more information, see the following topics:

For more information, see the following sections in the C# Language Specification:

  • 1.6.6.1 Parameters

  • 5.1.4 Value parameters

  • 5.1.5 Reference parameters

  • 5.1.6 Output parameters

  • 10.6.1 Method parameters

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker