View Plaincopy to Clipboardprint?
- int a = ten, B = 20;
- void swap (int x, int y)
- {
- int temp = x;
- x = y;
- y = temp;
- }
If you simply call this swap, such as swap (A, b), then you simply cannot exchange the values of the two variables, because both x and Y are formal parameters, and X and Y are freed when the swap returns. But if this is the definition of swap:
View Plaincopy to Clipboardprint?
- void Swap (int& x, int& y)
- {
- int temp = x;
- x = y;
- y = temp;
- }
The same as x and A,y and B point to the same memory address, then the operation of X is equivalent to the operation of A. So in C #, this effect is obvious for value types.
View Plaincopy to Clipboardprint?
- Class Program
- {
- static void Test (ref int b)
- {
- b = 2;
- }
- static void Main (string[] args)
- {
- int b = 1;
- Test (ref B);
- Console.WriteLine (b);
- }
- }
The output at this point is 2, that is, b in the test method points to the same memory address as B in main, then the operation on TEST.B is the main.b operation. If you change the program to:
View Plaincopy to Clipboardprint?
- Class Program
- {
- static void Test (int b)
- {
- b = 2;
- }
- static void Main (string[] args)
- {
- int b = 1;
- Test (b);
- Console.WriteLine (b);
- }
- }
Then the output is still 1, because test.b is not a main.b reference, that is, a single parameter. Now look at the effect of the reference type:
View Plaincopy to Clipboardprint?
- Class TestClass
- {
- public int B;
- }
- Class Program
- {
- static void Test (TestClass b)
- {
- B.B = 2;
- }
- static void Main (string[] args)
- {
- TestClass B = new TestClass ();
- b.b = 1;
- Test (b);
- Console.WriteLine (B.B);
- }
- }
The above code, the output is 2, because B is a reference type, when you only need to modify the members of B, add the same as the REF keyword. The reference type itself does not contain data, and it only maintains a reference to the data.
Therefore, using the ref parameter, the effect on a value type object is obvious, and for reference types, you do not need to use the REF keyword if you want to modify the data inside the reference type, otherwise, when the called function internally needs to change the reference itself, such as to reposition the reference to the object inside the function, You need to use the REF keyword.
C # Fundamentals: Value types, reference types, and ref keywords