7

I created the following class:

namespace Prototype.ViewModel.MyVM
{
    public clas TheVm
    {
        List<Tuple<string, bool>> list = new List<Tuple<string, bool>>();
        public List<Tuple<string, bool>> List 
        { 
            get { return this.list; } 
            set { this.list = value; } 
        }
    }
}

In another code file, I'm trying modify one of the values of the encapsulated List> object:

for (int i = 0; i < anotherList.Count; i++)
{
    TheVM.List[i].Item2 = (anotherList[i].Item2 == 1);
}

But I get the following error message:

Property or indexer 'Tuple.Item2' cannot be assigned to “--” it is read only.

How can I solve that?

Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
Platus
  • 1,753
  • 8
  • 25
  • 51
  • 4
    As the error is trying to tell you, you can't do that; tuples are immutable. – SLaks Jan 30 '17 at 15:31
  • 3
    See [Why Tuple's items are ReadOnly?](http://stackoverflow.com/questions/3131400/why-tuples-items-are-readonly) – stuartd Jan 30 '17 at 15:32
  • [MSDN](https://msdn.microsoft.com/en-us/library/dd268536(v=vs.110).aspx): "You can retrieve the values of the tuple's components by using the **read-only** Item1 and Item2 instance properties." – p.s.w.g Jan 30 '17 at 15:32
  • In other words...error tells you that you cant edit tuple item. You need to create new one. `TheVM.List[i].Item2 = new Typle(TheVM.List[i].Item1, (anotherList[i].Item2 == 1));` – Renatas M. Jan 30 '17 at 15:33

2 Answers2

11

You will need to create a new Tuple as they are immutable:

for (int i = 0; i < anotherList.Count; i++)
{
    TheVM.List[i] = new Tuple<string, bool>(TheVM.List[i].Item1, anotherList[i].Item2 == 1);
}

This being said, I would recommend against using Tuples for view models.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

If you need to change one part of the tuple after it is created, you don't need Tuple, just create you own class:

public class MyTuple
{
   public MyTuple(string item1, bool item2)
   {
     Item1 = item1;
     Item2 = item2; 
   }
   public string Item1 {get;set;}
   public bool Item2 {get;set;}
}

After that you could define your List as :

public List<MyTuple>> List

and will be able to change Item1/Item2

Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49