C # function parameter passing (by value and reference)

Source: Internet
Author: User

The data type in C #. Two categories of score types and reference types.

Value type: A value that stores data directly, stored in an in-memory stack (stack)

Reference type: Stores a reference to a value that is actually stored as a memory address. The save of the reference type is divided into two blocks, and the actual value is saved in the managed heap (heap). The memory address of the actual value is saved in the stack

When you use a reference type, locate the address in the stack, and then find the actual value in the heap.

This means that the stack and heap are used when saving reference types, but when using reference types we actually use only the values in the stack, and then indirectly access the values in the heap by this value

C # Predefined simple types, such as Int,float,bool,char, are value types, and enum (enum), struct (struct) is also a value type

A string, an array, and a custom class are all reference types. The string is a special reference type. C # adds a constant character to it.

C # function parameters if not added ref,out such a modifier modifier explicitly declaration parameter is passed by reference, by default, is the value of the pass.

One of the issues to note here is whether the type of the parameter is a value type or a reference type, and passing arguments with a value or a reference pass is two different concepts.

If there is void funtest (int [] array) and void funtest (int a)
These two functions. The parameter array is a reference type, and a is a value type. But they are passed by value.

Let's give an example to illustrate

Pass parameters by value:

Class Program

{

public static void changeint (int num)

{

num = 123;

}

public static void Changearray (int[] array)

{

Array[0] = 10;

Array = new int[] {6, 7, 8, 9};

}

static void Main (string[] args)

{

int anum = 1;

Int[] Aarray = {1, 2, 3};

Changeint (Anum);

Changearray (Aarray);

Console.WriteLine ("Value of num:" + anum);

Console.Write ("Value of Aarray:");

foreach (int i in Aarray)

Console.Write (i + "");

}

}

The result is: value of anum:1

Value of Aarray:10 2 3

It might be a little strange to see the results. We generally think that value is passed as a copy of the value, and then no matter what changes are made to the parameters in the function, the value before the parameter is not affected, so anum does not become 123, still 1.

But Aarray[0] Why did it become 10?

We're talking about the reference type in memory is saved as two parts, one is the memory address in the stack, and the other is the actual value in the heap. When we use only the value in the stack, we assume that the value in the stack is 0XABCDEFGH
, just say Aaraay point to it. So when we pass the value, we copy the value of the stack to another copy, if it's an array point. The value of copy Anum is 11.

But when we manipulate a value such as a memory address, we do not manipulate it directly as an integer, but only through it to find the actual value in the heap.

So we array[0] = 10. Change the value of the array in the heap, actually. But array = new int []
{6,7,8,9} has no effect on previously transmitted aarray. The significance of this operation is to re-open a piece of memory in the heap, preserving the value 6,7,8,9.
The address of this memory is assigned to an array, and its previous value of 0XABCDEFGH is rewritten. But the value of Aarray refers to the stack value remains unchanged, still 0xabcdefgh

Passing parameters by reference

Can be specified explicitly with out or ref. They can be generalized for most of the time, just a small difference.

First Use ref for example, and also use the above example, just add a keyword ref

Class Program

{

public static void Changeint (ref int num)

{

num = 123;

}

public static void Changearray (ref int[] array)

{

Array[0] = 10;

Array = new int[] {6, 7, 8, 9};

}

static void Main (string[] args)

{

int anum = 1;

Int[] Aarray = {1, 2, 3};

Changeint (ref anum);

Changearray (ref Aarray);

Console.WriteLine ("Value of num:" + anum);

Console.Write ("Value of Aarray:");

foreach (int i in Aarray)

Console.Write (i + "");

}

}

The result is: value of anum:123

Value of Aarray:6 7 8 9

It's a completely different result than by the value of the pass.

num = 123 We are easy to understand. Why do we change the value of Aarray?

When passed by reference, the value in the stack that Aarray points to does not replicate a copy, but is passed directly to the past. So array[0]= 10 also changes the heap 1 2 3
The value to 10 2 3, if

No array = new int [] {6,7,8,9}
This statement, the result is exactly the same as the value passed above. But there's a difference after that, and we know what it means, a new memory in the heap

The value is 6 7 8 9, and the value of the stack that Aarray points to is rewritten, instead pointing to the memory address where 6 7 8 9 is saved. that contains 10 2
3 of that piece of memory actually continues to exist, but no one references it. The garbage collector will recycle it.

Add:

The small difference between out and ref

The arguments passed in ref must be assigned first.

As in the example above, if you write this

int num;

Changeint (ref int num);

Error, you must first give num a value of 1.

And the parameters that are passed in out can be assigned without first assigning values.

Out num;

Changeint (out int num); it's right.

Another difference is that if you use out the Changeint function must have somewhere to assign num, and ref does not necessarily need to assign num in the function

In fact, the purpose of doing so is well understood. C # to ensure that NUM must have a value in any case, it cannot be empty.

Because with ref, a parameter must be guaranteed to have a value before the function is called, so it must not be required to be assigned again in the function.

It must be guaranteed to be a value in the function if it is not guaranteed to have a value before calling the function.

Changeint (ref int num) and changeint (out int num) are different, but coexist and cannot be used as two different functions

and changeint (int num) and the above two functions are completely different, can be put together to coexist

In this case the invocation of the time ref, out such a keyword can not be saved. Must match

C # function parameter passing (by value and reference)

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.