Why use ref for array parameters in C #?

I read the Pass Arrays page using ref and out (C # Programming Guide) and wondered why we need to define an array parameter as a ref parameter when it is already a reference type. Will the ringer function appear in the caller function?

+6
source share
2 answers

Will the called party function in the calling party function be changed?

Changes in the contents of the array will be reflected in the method of the caller, but there will be no changes in the parameter itself. For example:

public void Foo(int[] x) { // The effect of this line is visible to the caller x[0] = 10; // This line is pointless x = new int[] { 20 }; } ... int[] original = new int[10]; Foo(original); Console.WriteLine(original[0]); // Prints 10 

Now, if we changed Foo to have a signature:

 public void Foo(ref int[] x) 

and changed the call code to:

 Foo(ref original); 

then he will print 20.

It is very important to understand the difference between the variable and the object to which its value belongs, as well as between the change in the object and the change in the variable.

See the article on passing parameters in C # for more information.

+24
source

If you only plan to change the contents of the array, then you are right. However, if you plan to change the array itself, you must follow the link.

For instance:

 void foo(int[] array) { array[0] = 5; } void bar(int[] array) { array = new int[5]; array[0] = 6; } void barWithRef(ref int[] array) { array = new int[6]; array[0] = 6; } void Main() { int[] array = int[5]; array[0] = 1; // First, lets call the foo() function. // This does exactly as you would expect... it will // change the first element to 5. foo(array); Console.WriteLine(array[0]); // yields 5 // Now lets call the bar() function. // This will change the array in bar(), but not here. bar(array); Console.WriteLine(array[0]); // yields 1. The array we have here was never changed. // Finally, lets use the ref keyword. barWithRef(ref array); Console.WriteLine(array[0]); // yields 5. And the array length is now 6. } 
+5
source

Source: https://habr.com/ru/post/955525/


All Articles