Reference transfer and value transfer in C #

Source: Internet
Author: User

1. Passing Parameters

You can pass parameters either by value or by reference. Passing parameters by reference allows function members (methods, attributes, indexers, operators, and constructors) to change the value of the parameter and keep the changes.

Ii. Pass value type parameters

A Value Type Variable directly contains its data, which is different from a reference type variable, which contains references to its data. Therefore, passing a value type variable to a method means passing a copy of the variable to the method. Changes to parameters in the method have no impact on the raw data stored in the variable. If you want to change the value of a parameter in the called method, you must use the ref or out keyword to pass this parameter through reference. For simplicity, the following example uses ref.

1. Pass the value type by value:

Code

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 ("The value inside the method: {0}", x);} static void Main () {int n = 5; System. console. writeLine ("The value before calling the method: {0}", n); SquareIt (n); // Passing the variable by value. system. console. writeLine ("The value after calling the method: {0}", n );}}

Variable n is a value type and contains its data (value: 5 ). When SquareIt is called, the content of n is copied to parameter x, and the square of this parameter is obtained in the method. However, in Main, the value of n is the same before and after the SquareIt method is called. In fact, changes in the method only affect the local variable x.

2. Pass the value type through reference

The following example uses the ref keyword to pass parameters. The parameter value is changed after the method is called.

Code

Class PassingValByRef {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 ("The value inside the method: {0}", x);} static void Main () {int n = 5; System. console. writeLine ("The value before calling the method: {0}", n); SquareIt (ref n); // Passing the variable by reference. system. console. writeLine ("The value after calling the method: {0}", n );}}

In this example, n is not passed, but a reference to n. The x parameter is not of the int type. It is a reference to the int type (n in this example ). Therefore, when square is obtained for x in the method, the actually calculated square is the item referenced by x: n.

3. Exchange Value Type

A common example of changing the value of a passed parameter is the Swap method. In this method, two variables x and y are passed, and the method exchanges their content. Parameters must be passed to the Swap method through reference; otherwise, the local copy of the parameters will be processed in the method. The following is an example of the Swap method using the reference parameter:

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

Iii. Pass reference type parameters

Variables of the reference type do not directly contain their data; they contain references to their data. When a parameter of the reference type is passed through a value, it is possible to change the data pointed to by the reference, such as the value of a certain type of member. However, you cannot change the reference value. 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, use the ref or out keyword to pass the parameter. For simplicity, the following example uses ref.

1. Pass the reference type by value

The following example shows how to pass the arr parameter of the reference type to the Change method by using a value. Because this parameter is a reference to arr, it is possible to change the value of the array element. However, if you try to reassign a parameter to a different memory location, this operation is only valid in the method and does not affect the original variable arr.

Code

Class PassingRefByVal {static void Change (int [] pArray) {pArray [0] = 888; // This change affects the original element. pArray = new int [5] {-3,-1,-2,-3,-4}; // This change is local. system. console. writeLine ("Inside the method, the first element is: {0}", pArray [0]);} static void Main () {int [] arr = {1, 4, 5}; System. console. writeLine ("Inside Main, before calling the method, the first element is: {0}", arr [0]); Change (arr); System. console. writeLine ("Inside Main, after calling the method, the first element is: {0}", arr [0]);}

In the previous example, the array arr is of the reference type and is passed to the method without using the ref parameter. In this case, a copy of the reference pointing to arr is passed to the method. The output display method may change the content of the array element from 1 to 888. However, using the new operator in the Change method to allocate a new part of memory will make the variable pArray reference the new array. Therefore, any subsequent changes do not affect the original array arr (it is created in Main ). In fact, two arrays are created in this example, one in Main and the other in the Change method.

2. Pass the reference type through reference

In this example, except that the ref keyword is used in the method header and call, it is the same as the previous example. Any changes made in the method will affect the original variables in the calling program.

Code

Class PassingRefByRef {static void Change (ref int [] pArray) {// Both of the following changes will affect the original variables: pArray [0] = 888; pArray = new int [5] {-3,-1,-2,-3,-4}; System. console. writeLine ("Inside the method, the first element is: {0}", pArray [0]);} static void Main () {int [] arr = {1, 4, 5}; System. console. writeLine ("Inside Main, before calling the method, the first element is: {0}", arr [0]); Change (ref arr); System. console. writeLine ("Inside Main, after calling the method, the first element is: {0}", arr [0]);}

All changes made in the method affect the original array in Main. In fact, the original array is reallocated using the new operator. Therefore, after the Change method is called, any reference to arr will point to the array of the five elements created in the Change method.

3. Exchange two strings

The exchange string is a good example of passing a reference type parameter through reference. In this example, the str1 and str2 strings are initialized in Main and passed to the SwapStrings method as parameters modified by the ref keyword. The two strings are exchanged in this method and in Main.

Code

Class SwappingStrings {static void SwapStrings (ref string s1, ref string s2) // The string parameter is passed by reference. // Any changes on parameters will affect the original variables. {string temp = s1; s1 = s2; s2 = temp; System. console. writeLine ("Inside the method: {0} {1}", s1, s2);} static void Main () {string str1 = "John "; string str2 = "Smith"; System. console. writeLine ("Inside Main, before swapping: {0} {1}", str1, str2); SwapStrings (ref str1, ref str2); // Passing strings by reference System. console. writeLine ("Inside Main, after swapping: {0} {1}", str1, str2 );}}

In this example, parameters must be passed through references to affect variables in the calling program. If the ref keyword is removed from both the method header and method call, no changes will be made to the calling program.

Iv. Transfer of reference data values (Transfer of duplicate copies)

By default, the class creates a superficial copy using the MemberwiseClone method. The method is to create a new object and then copy the non-static fields of the current object to the new object. If the field is of the value type, perform a step-by-step copy on the field. If the field is of reference type, the referenced object is copied but not referenced. Therefore, the original object and its counterparts reference the same object. Deep copy, that is, the ICloneable interface. ICloneable can be used for deep copy and light copy. These are concepts, but we need to understand:

Code

Class ClassA: ICloneable {public string str; public SubClass subclass; public ClassA () {str = "classA str"; subclass = new SubClass () ;}// deep copy, multi-layer MemberwiseClone () is not available to fully implement deep replication of public object Clone () {// this. a = (string) this. a. clone (); // this. B = (B) this. b. clone (); var ne = new ClassA (); ne. str = this. str; ne. subclass = (SubClass) this. subclass. clone (); // this. B still fails to return ne; // return this. memberwiseClone () ;}} class SubClass: ICloneable {public string str; public SubClass () {this. str = "subclass str";} // deep replication. Because there is only one layer, you can use the MemberwiseClone () method to public object Clone () {this. str = (string) this. str. clone (); return this. memberwiseClone ();}

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.