Are values ​​in LINQ expressions passed by reference?

I am reading a book about LINQ, and there is an example:

    static class QueryReuse
    {
       static double Square(double n)
       {
         Console.WriteLine("Computing Square("+n+")...");
         return Math.Pow(n, 2);
       }
       public static void Main()
       {
         int[] numbers = {1, 2, 3};
         var query =
                  from n in numbers
                  select Square(n);

         foreach (var n in query)
              Console.WriteLine(n);

         for (int i = 0; i < numbers.Length; i++)
              numbers[i] = numbers[i]+10;

         Console.WriteLine("- Collection updated -");

         foreach (var n in query)
             Console.WriteLine(n);
    }
}

with the following output:

Computing Square(1)...
1
Computing Square(2)...
4
Computing Square(3)...
9
- Collection updated -
Computing Square(11)...
121
Computing Square(12)...
144
Computing Square(13)...
169

Does this mean that "numbers" are passed by reference? Does this behavior have to do something with lazy execution and exit? Or am I mistaken here?

+3
source share
5 answers

Do this with lazy execution. Each time you repeat the request, he again looks at numbers. Indeed, if you change the value of the last element numbersduring query execution, you will also see this change. All this changes the contents of the array.

, numbers , , . , numbers :

numbers = new int[] { 10, 9, 8, 7 };

.

, , :

int x = 3;

var query = from n in numbers
            where n == x
            select Square(n);

x , ... x . , :

var query = numbers.Where(n => n == x)
                   .Select(n => Square(n));

, x , numbers - .

+7

numbers . , .

, ?

var arr = new[]{1,2,3,};
var q = arr.Select(i=>i*2);
Console.WriteLine(string.Join(", ",q.ToArray())); //prints 2, 4, 6
arr[0]=-1;
Console.WriteLine(string.Join(", ",q.ToArray())); //prints -2, 4, 6
// q refers to the original array, but that array has changed.
arr = new[]{2,3,4};
Console.WriteLine(string.Join(", ",q.ToArray())); //prints -2, 4, 6
//since q still refers to the original array, not the variable arr!

, , , , .

:

var arr = new[]{1,2,};
var arr2 = new[]{1,2,};
var q = from a in arr
        from b in arr2
        select a*b;

// q is 1,2,2,4
arr = new[]{0,1}; //irrelevant, arr reference was passed by value
// q is still 1,2,2,4

arr2 = new[]{0,1}; //unfortunately, relevant
// q is now 0, 1, 0, 2

, . (arr.Select...), . , , , , . ? , , .

+6

- , .

, , , . , , , , .

+3

, numbers closure .

0

, numbers , , LINQ, .

, - / LINQ.

-1
source

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


All Articles