C# – The Left-Hand Side of an Assignment Must Be a Variable, Property or Indexer

c++

I'm getting an error and I don't know why:

static void decoupeTableau(IEnumerable<int> dst, IEnumerable<int> src)
{
    for (int i = 0; i < src.Count() && i < 4; ++i)
        dst.ElementAt(i) = src.ElementAt(i); // Here
}

Error:

The left-hand side of an assignment must be a variable, property or indexer

Why I'm getting it?

Best Answer

Why I'm getting it ?

Because you've got an assignment operator where the left hand side is a method call. What did you expect that to do? What code would that call? An assigment has to either set the value of a variable, or call a setter for a property. This isn't doing either of those things.

Basically, you can't do this - and for IEnumerable<T> it doesn't even make sense, as it can be read-only, generated etc.

Perhaps you want an IList<int> instead:

static void DecoupeTableau(IList<int> dst, IEnumerable<int> src)
{ 
    int i = 0;
    foreach (var value in src.Take(4))
    {
        dst[i] = value;
        i++;
    }
}

Note how this code is also potentially much more efficient - calling Count() and ElementAt in a loop can be very expensive. (For example, with a generator, each time you call Count() you have to iterate over the whole stream - so it wouldn't even complete if this were a theoretically infinite stream, such as a random sequence of integers.)

Related Question