Application of ref in C # Parameters

Source: Internet
Author: User

Passing parameters (downmoon) through values and references in C)

 

In C #, parameters can be passed 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. To pass parameters through references, use the ref or out keyword. For simplicity, only the ref keyword is used in this topic example. For information on the differences between ref and out, see, use ref and out to pass arrays.

This topic includes the following chapters:

  • Pass value type parameters
  • Pass reference type parameters

 

It also includes the following examples:

Example Demo Whether to use ref or out
1 Pass value type by value No
2 Pass value type by reference Yes
3 Exchange value type (two integers) Yes
4 Pass reference type by value No
5 Pass reference type by reference Yes
6 Exchange reference type (two strings) Yes

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 parameter value of the called method, you must use the ref or out keyword to pass this parameter through reference. For simplicity, the following example uses ref.

Example 1: Pass the value type by value

The following example shows how to pass a value type parameter through a value. Pass the variable Myint to the squareit method by using the value. Any changes made in the 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 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 is a value type and contains its data (value 5 ). When squareit is called, the content of Myint is copied to parameter X, and the square of this parameter is obtained in the method. However, in Main, the value of Myint is the same before and after the squareit method is called. In fact, changes in the method only affect the local variable X.

Example 2: Pass the value type through reference

The following example uses the ref keyword to pass parameters, and the others are the same as "Example 1. The parameter value is changed after the method is called.

// 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, the value of Myint is not passed, but the reference of Myint. The X parameter is not of the int type. It is a reference to the int type (in this example, it is a reference to the Myint type ). Therefore, when square is obtained for X in the method, the actually calculated square is the item referenced by X: Myint.

Example 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;

}

 

When calling this method, use the ref keyword in the call, as shown below:

Swapbyref (Ref I, ref J );

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.

Example 4: Pass reference type by value

The following example shows how to pass the reference type parameter myarray to the change method through the value. Because this parameter is a reference to myarray, it is possible to change the value of the array element. However, if you try to allocate parameters to different memory locations, this operation is only valid in 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 previous example, the array myarray is of the reference type and is passed to the method without using the ref parameter. In this case, a copy pointing to the reference of myarray is passed to the method. The output display method may change the content of an 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 arr reference the new array. Therefore, any subsequent changes will not affect the original array myarray (it was created in main ). In fact, two arrays are created in this example, one in main and the other in the change method.

Example 5: 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 "Example 4. Any changes made 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 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 myarray will point to the array of the five elements created in the change method.

Example 6: swap 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.

// 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, 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.

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.