Passing parameters by value and reference in C # (Downmoon)

Source: Internet
Author: User
Tags copy header reference

Passing parameters by value and reference in C # (Downmoon)
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 parameter and maintain the change. To pass parameters by reference, use the ref or out keyword. For the sake of simplicity, only the REF keyword is used in the example in this topic. For information about the differences between ref and out, see, use ref and out to pass an array.

This topic includes the following chapters:

Passing Value type parameters
Passing reference type parameters
It also includes the following examples:

Example shows whether to use ref or out
1 passing value types by value No
2 passing a value type by reference is
3 Exchange value types (two integers) are
4 Passing a reference type by value No
5 passing reference types by reference is
6 Exchange reference types (two strings) are

Passing Value type parameters
A value type variable contains its data directly, unlike 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. A change to a parameter that occurs within a method has no effect on the raw data stored in the variable. If you want the method you are calling to change the parameter value, you must pass it by reference with a ref or out keyword. For simplicity's sake, the following example uses Ref.

Example 1: Passing Value types by value
The following example demonstrates passing a value type parameter by value. Pass the variable myInt to the method SquareIt by value. Any changes that occur within a method have no effect 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'll not affect the original value of Myin t.    {        x *= x;        Console.WriteLine ("The value inside: {0}", x);   }    public static void Main ()     {        int myInt = 5;         Console.WriteLine ("The value before calling the method: {0}",         & nbsp;  myInt);        SquareIt (myInt);  //Passing myInt by value.         Console.WriteLine ("The value after calling: {0}",            myInt);    }} Output
The value before calling the Method:5the value inside the method:25the value after calling the Method:5 code discussion
Variable myInt is a value type containing its data (value 5). When SquareIt is invoked, the contents of the myInt are copied into the parameter x, and the argument is squared within the method. In Main, however, the value of the myInt is the same before and after the SquareIt method is invoked. In fact, changes that occur within a method affect only the local variable x.

Example 2: Passing a value type by reference
The following example is the same as "Example 1" in addition to passing parameters using the REF keyword. The value of the parameter changes after the method is invoked.

PassingParams2.cs using system;class passingvalbyref{    static void SquareIt (ref int x)   & nbsp The parameter x is passed by reference.   //Changes to x would affect the original value of MYINT.&NBSP ;   {        x *= x;        Console.WriteLine ("The value inside: {0}", x);   }    public static void Main ()     {        int myInt = 5;         Console.WriteLine ("The value before calling the method: {0}",         & nbsp;  myInt);        SquareIt (ref myInt);  //Passing myInt by reference.        Console.WriteLine ("The value after calling: {0}",            myInt);   }} output
The value before calling the Method:5the value inside the method:25the value after calling the METHOD:25 code discussion
In this example, a reference to the myInt is passed instead of the myInt value. Parameter x is not an int type, it is a reference to int (in this case, a reference to myInt). Therefore, when squaring the X in the method, the actual square is the item that x refers to: MyInt.

Example 3: Exchanging value types
A common example of changing the value of a passed parameter is the Swap method, in which the X and y two variables are passed, and the methods are exchanged for their contents. Parameters must be passed to the Swap method by reference, otherwise the local copy of the parameter will be processed within the method. The following is an example of a Swap method that uses reference parameters:

static void Swapbyref (ref int x, ref int y) {int temp = x;    x = y; y = temp;} When calling this method, use the REF keyword in the call, as follows:

Swapbyref (ref I, ref j); Passing reference type parameters
A variable of a reference type does not directly contain its data, it contains a reference to its data. When passing a parameter of a reference type by value, it is possible to change the data that the reference points to, such as the value of a member of a class. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for the new class and keep it out of the block. To do this, pass the parameter using the ref (or out) keyword. For simplicity's sake, the following example uses Ref.

Example 4: Passing a reference type by value
The following example shows a parameter myarray that passes a reference type by value to the change method. Because this parameter is a reference to myarray, it is possible to change the value of the array element. However, when an attempt is made to reassign a parameter to a different memory location, the operation is only valid within the method and does not affect the original variable myarray.

PassingParams4.cs//Passing an array to alpha without the ref keyword.//Compare the results to those of Example of 5. Using System;class passingrefbyval {   static void Change (int[] arr)    {    & nbsp arr[0]=888;  //This change affects the original element.      arr = new Int[5] {-3,- 1,-2, -3, -4};  //This is local.      Console.WriteLine ("Inside", t He-is: {0} ', arr[0]);  }      public static void Main ()   & nbsp {      int[] myarray = {1,4,5};      Console.WriteLine ("Inside Main, before calling the method, the "the", "the", "" "," "", "" "" "," myarray [0]);      change (myarray); nbsp;     Console.WriteLine ("Inside Main, after calling," the "the", "the" and "the", "the" is: {0} ", Myarra y [0]);  }} output
Inside Main, before calling the method, the "the", the "the" and "the", "the", "the", "the" Er calling the method, the is:888
In the previous example, the array was myarray as a reference type and passed to the method without using the ref parameter. In this case, a copy of the reference to the MyArray is passed to the method. The output display method may change the contents of the array element (from 1 to 888). However, using the new operator in the change method to allocate a fresh portion of memory will cause the variable arr to refer to the new array. Therefore, any subsequent changes will not affect the original array myarray (which is created within Main). In fact, this example creates two arrays, one inside Main and one within the change method.

Example 5: Passing reference types by reference
This example is the same as "Example 4" in addition to using the REF keyword in the method header and call. Any changes that occur within a method affect the original variable in the calling program.

PassingParams5.cs//Passing an array to a and the ref keyword.//Compare the results to those of Example 4.usi ng System;class passingrefbyref {   static void change (ref int[] arr)    {    & nbsp Both of the following changes would affect the original variables:      arr[0]=888; &nbsp ;    arr = new Int[5] { -3,-1,-2, -3, -4};      Console.WriteLine ("Inside The Met Hod, the "the" is: {0} ", Arr[0]);  }      public static void Main ()  &nbs p;  {      int[] myarray = {1,4,5};      Console.WriteLine (" Inside Main, before calling the method, the the-the-I-is: {0} ', myarray [0]);      Change (ref myarray);      Console.WriteLine ("Inside Main, after calling the method, the 0} ", myarray [0]);  }} Output
Inside Main, before calling the method, the "the", the "the" and "the", "the", "the", "the" Er calling the method, the "A" is:-3 Code Discussion
All changes that occur within a method affect the original array in Main. In effect, the original array was reassigned using the new operator. Therefore, after calling the change method, any references to MyArray will point to an array of five elements created in the change method.

Example 6: Swapping two strings
The swap string is a good example of passing reference type parameters by reference. In this example, the str1 and str2 two strings are initialized in Main and passed to the Swapstrings method as parameters decorated by the ref keyword. The two strings are exchanged within the method and inside Main.

passingparams6.csusing system;class swappinstrings{    static void Swapstrings (ref string S1, ref String s2)    //The string parameter x is passed by reference.   //no changes on Paramet ERS would affect the original variables.    {        String temp = s1;& nbsp;       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 smithinside the Method:smith, Johninside Main, after Swapping:smith, John code Discussion
In this example, you need to pass parameters 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 occur in the calling program.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.