mina shaker

mina shaker

  • 1.6k
  • 125
  • 6.7k

why i am reciving Error CS8157 in below code?

Dec 3 2022 3:48 AM

hi 

i made a function that takes an array as an argumente and checks the even numbers only and add them to an new array and then i tried to return the new array by refrence but i got the error:

Cannot return 'x' by reference because it was initialized to a value that cannot be returned by reference

the code is 

        static ref int[] loop(ref int[] array)
        {
            int[] d = { };

            ref int[] x = ref d;

            for (int i = 0; i < array.Length; i++)
            {

                if (array[i] %2 != 0)
                {
                    x[i] = array[i];  
                }

            }
            return ref x;
        }

please can anyone help me to understand what happened 

note i know that the same thing can be done uing the out parameter int the function signature but i want to make it using ref


Answers (1)