I'm new to C# and I don't understand how to achive something like this (as I would do in a language like C++):
List<Element> _elements = ... // Created before
for (var i = 0; i < _elements.Count; i++)
{
_elements[i].Color = Color.Black;
}
It gives me: Indexer access returns temporary value. Cannot modify struct member when accessed struct is not classified as a variable
, which I find weird because I have specified the field with { get; set; }
, shouldn't the example above "use" the setter?
I only get it to work by creating a new instance and copying the other values of my class Element
(which contains Color
and Value
), which is weird, because the error message above said indexer returns a temporary value that I would then just overwrite.
It also feels wrong, and would be tedious for any larger data types:
List<Element> _elements = ... // Created before
for (var i = 0; i < _elements.Count; i++)
{
_elements[i] = new Element(_elements[i].Value, Color.Black);
}
Is the problem that I am using List? Or should I iterate in some other way?
Element class is super simple:
public struct Element
{
public long Value { get; set; }
public Color Color { get; set; }
public Element(long value, Color color)
{
Value = value;
Color = color;
}
}
Thanks in advance.
EDIT
This was edited to better show that this question is not about assignment, but that _elements
is already created.