C # value type, reference type, value transfer, and reference Transfer
When it comes to parameter passing, the value type and reference type must be clarified:
( For ease of expression, I name the content stored in the heap as the object in the heap, And the content stored in the stack as the object in the stack. )
The value type is stored in the stack and accessed directly. If: Int A = 0; int B =; The two stack objects are generated.
The reference type needs to be explicitly allocated in the heap and cannot be accessed directly. You need to allocate a stack object (C ++ is a pointer and C # Is a reference) in the stack to the object in the heap. .
If:
Stringbuilder strb = new stringbuilder ();
Stringbuilder strb2 = strb;
There is only one heap object in the heap, but there are two objects in the stack pointing to objects in the heap.
It can be seen that every variable is a stack object. Whether it is a value type or a reference type, the stack object of the value type is its content, and the stack object of the reference type is only an address pointing to the object in the stack.
Determine whether it is a value type or a reference type:
IntA1 = 10;
Stringbuilder strb1 =NewStringbuilder ("ABC ");
IntA2 = A1;
Stringbuilder strb2 = strb1;
Bool BL1 = Object . Referenceequals (a1, a2 ); // False Is a Value Type ( Because the value type needs to be boxed )
Bool Bl2 = Object . Referenceequals (strb1, strb2 ); // True Is of reference type
Parameter transfer value transfer and reference transfer.
Generally, it is a value transfer when the ref and out parameters are not explicitly specified..
Value Transfer: transfers the object's value copy. ( That is, when the parameter object in the function is called, the copy of the object in the stack of the object is passed. )
Reference transfer: transmits the address of the object in the stack. ( That is, the parameter object in the function and the object passed during the call are exactly the objects in the same stack. )
In this example, the value transfer is different from the address transfer:
private void button2_click ( Object sender, system. eventargs e)
{< br> stringbuilder strb1 = New stringbuilder ();
stringbuilder strb2 = New stringbuilder ();
test1 (strb1);
Test2 ( ref strb2);
string str1 = strb1.tostring (); // str1 Value : ""
String Str2 = strb2.tostring (); // Str2 Value : "BC"
}
VoidTest1 (stringbuilder strb)
{
// StrbAndStrb1Is an object in two stacks, but points to the same address. This operation is to change the object in the heap.
Strb. append ("");
// Here we will Strb Point to a new heap object. Strb1 The objects in the stack to be directed are irrelevant.
Strb = New Stringbuilder ("B ");
Strb. append ("C ");
}
Void Test2 ( Ref Stringbuilder strb)
{
// Here Strb And Strb2 Is an object in the same stack, so it changes Strb So that it points to another object is also changed Strb2
Strb = New Stringbuilder ("B ");
Strb. append ("C ");
}