Search code examples
c#arraysselectvalue-typereference-type

C# select doesn't change value of array


Can anyone explain to me why this code changes Matrix internal array:

    public Labyrinth(int width, int height)
    {
        baseMatrix = new char[width][];

        for (int i = 0; i<baseMatrix.Length; ++i)
        {
            baseMatrix[i] = new char[height];
        }

        mod(baseMatrix[0]);
    }

    void mod(char[] x)
    {
        x[0] = 'a';
    }

and this doesn't change anything:

    public Labyrinth(int width, int height)
    {
        baseMatrix = new char[width][];

        for (int i = 0; i<baseMatrix.Length; ++i)
        {
            baseMatrix[i] = new char[height];
        }

        baseMatrix.Select(x => x[0] = 'a');
     }

I don't understand, both the select and the function take a char[] element, this i believe is passed for value, then x[0] should be modified in both case, where i'm wrong?


Solution

  • The reason is that you haven't materialized the result of the Select call. The last line of code is merely a lazy-evaluated expression. Since its value has never been requested, the expression has not been executed and therefore no modification was made to the array.

    You have to do something, like call ToList(), to force the expression evaluate.

    baseMatrix.Select(x => x[0] = 'a').ToList();
    

    On a side note, you should really refrain from doing things this way. LINQ operators are intended to be side-effect free, and setting an array content inside a Select call can cause bugs.