Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property or indexer cannot be assigned to “--” it is read only C# List<Tuple<string, bool>>

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?

like image 272
Platus Avatar asked Jan 30 '17 15:01

Platus


2 Answers

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.

like image 189
Darin Dimitrov Avatar answered Nov 10 '22 01:11

Darin Dimitrov


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

like image 1
Maksim Simkin Avatar answered Nov 10 '22 01:11

Maksim Simkin