In the previous article, we talked about "Heap" and "stack". In this article, we mainly talk about the differences between value types and reference types when they are passed as parameters.
There are two main scenarios:
1. Pass the Value type (Passing Value Types)
2. Pass the Reference type (Passing Reference Types)
First, let's take a look at the first situation,Passing Value Types):
x = AddFive(+=
We have discussed the value type storage issue in the previous article, so we will not talk about it too much here.
We all know that the value type uses the data itself, so 5 will be copied to pValue. Therefore, the final value of x remains unchanged.
Note that if we copy a very large value type variable (such as a large struct) to the stack, this consumes a lot of memory space and processor processing cycle, because the "stack" space is not infinite.
How can this problem be solved? Let's look at an example.
= DoSomething(}
No. The DoSomething () method has a ref keyword. This introduces another situation in which we pass the value type. The value type is passed by reference.
No. At this time, pValue is an address pointer pointing to x.
Note that when we use a reference method to pass a value parameter, we access the source parameter itself. Any change to pValue is a change to x. The following code changes x. a to 12345.
= = voidDoSomething(=
Next let's take a look at another situation,Passing Reference Types):
x = = =
The output is 12345, and the result is changed. Copy the value of x (the address of the MyInt object on the "heap") to pValue so that both x and pValue point to the address of the MyInt object.
Since the value type can use the ref keyword, how does the reference type use the ref keyword? Okay. Let's take an example:
= + (x + (x Switcharoo(=
The execution result of the program is:
X is Animal: False
X is Vegetable: True
PValue points to x this time. Then, by changing the address of x, pValue also changes.
Now, we will introduce you here. If you have any questions or errors, please give us some advice and exchange.