Like other reference types, you can use an array as an output parameter, using the out keyword. The out keyword indicates that you must assign a value to the array before returning from the method. Also, within the method, you cannot reference the array parameter before you assign a new value to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | static int FindFibsThrough(int numFibs, out int[] fibs){ // Can't reference element of array //int i = fibs[0]; // Can't assign to element of array //fibs[0] = 12; if (numFibs < 2) throw new Exception("Must return at least 2 numbers in sequence"); // Must assign new value to array before we return fibs = new int[numFibs]; fibs[0] = 0; fibs[1] = 1; int sum = 1; for (int i = 2; i < numFibs; i++) { fibs[i] = fibs[i - 1] + fibs[i - 2]; sum += fibs[i]; } return sum;} |
You must also use the out keyword when calling the method.
1 2 | int[] myFibs;int sum = FindFibsThrough(10, out myFibs); |

