Search code examples
c#settergettergetter-setter

c# jagged array getter and setter


I have a:

private bool[][] field
{
    get { return allfields[allfields.Count - 1]; }
    set { allfields.Add(value); generation++; }
}

and a:

if (field[x][y])
{
    field[x][y] = false;
}
else
{
    field[x][y] = true;
}

the if-clause seems to be working properly but the setter is not called in any way while setting... Is there any Idea of how to solve this (e.g. better setter) or at least a reason for this problem?

Thanks for help

P.S.:

field = nextfield.Clone() as bool[][];

is calling the setter...


Solution

  • A better approach is to use Indexer property as a public accessor to the array

    class BoolArray
    {
       public bool this[int raw, int column]
       {
           get
           {
               // access internal jugged array 
               if (_data[raw] == null)
               {
                   return false;
               }
    
               return _data[raw][column];   
           }
    
           set
           {
              if (_data[raw] == null)
              {
                 _data[raw] = new bool[Columns];
              }
    
              _data[raw][column] = value;
    
           } 
       }
    
       // Using a jugged array as storage
       private bool _data[][];
       ...
    }