I know this sounded stupid. But I gotta be doing something wrong here.
Say,
struct lala { private bool state1; public lala(bool state1) { this.state1 = state1; } public void SetState1ToTrue() { this.state1 = true; } public bool GetState1() { return this.state1; } }
Then somewhere…
List<lala> lalas = new List<lala>(); lalas.Add(new lala(false)); lalas.Add(new lala(false)); lalas[0].SetState1ToTrue(); // Why is it False??? Console.WriteLine(lalas[0].GetState1());
Are there any workarounds to this except changing it to:
List<lala> lalas = new List<lala>(); lalas.Add(new lala(false)); lalas.Add(new lala(false)); lala newLala = lalas[0]; newLala.SetState1ToTrue(); lalas[0] = newLala; // It's True, finally. Console.WriteLine(lalas[0].GetState1());
Which looked awful, unelegant and wasted 2 lines of code. If there’s any Linq-ish or Functional Programming-ish way in say 1 line of code that would be awesome.
The problem is in this line:
The first part, lalas[0], retrieves the first lala from the list, and does so as a new copy of it in an implicit variable. So your SetState1ToTrue operates on a lala that is then immediately discarded, and the one in the list remains the same. It’s the same as doing this:
If you make lala a class not a struct, so that it becomes a reference type, then the temporary variable (explicit or implicit) is a reference to the lala within the list.