list.Add is replacing

Im trying to generate a list of lists of lists of ints List<List<List<int>>>();. But every time it is suppose to add, it is replacing all items before.


int numeroDeInputs = 2;
    int numeroDeOutputs = 2;
    int numeroDeCamadas = 6; //layers

    List<int> genes;
    List<List<int>> GeneList;
    List<List<List<int>>> genotipo;



    void Start()
    {
        genotipo = new List<List<List<int>>>();
        GeneList = new List<List<int>>();
        genes = new List<int>();

        StartGenotipo();
        PrintGenotipo();
    }

	void StartGenotipo () {
        genotipo.Clear();
        for (int i = 0; i < numeroDeCamadas-1; i++)
        {
            GeneList.Clear();
            int tamanhoDoProx = numeroDeCamadas - i - 2 + numeroDeOutputs; //size of next layer
            for (int j = 0; j < tamanhoDoProx+1; j++)
            {
                genes.Clear();
                for (int k = 0; k < tamanhoDoProx; k++)
                {
                    genes.Add(Random.Range(0, tamanhoDoProx - 1));
                }
                GeneList.Add(genes);
            }
            genotipo.Add(GeneList);
        }
	}
    void PrintGenotipo()
    {
        string retorno = "";
        foreach (List<List<int>> lsLsI in genotipo)
        {
            retorno += "

(“;
foreach (List lsI in lsLsI)
{
retorno += "
[”;
foreach(int num in lsI)
{
retorno += num;
}
retorno += “]”;
}
retorno += “)”;
}
Debug.Log(retorno);
}


it should output in the console something like:

([015031][012350][130350])
([01234][42023][01210])
([0033][1020][1230])
([002][012][110])
([01][10][11])

instead of

([00][00][00])
([00][00][00])
([00][00][00])
([00][00][00])
([00][00][00])

When you add a list to a list, it adds a reference, not a copy. You’re not making a List of lists of lists at all, you’re making a list of multiple references to the same list (…of multiple references to the same list… etc).

So there are 2 fixes that spring to mind. You could try replacing

genes.Clear();

with

genes = new List<int>();

(and so on)

Alternatively, you could change your Add(list) calls so that they’re adding a copy.