I want to add objects in a List <T> when I select an item from a combobox, named cmbMaxim. The problem is I obtain a list with the same object (last object added). It's seems like new operator won't work and I obtain a reference to the same object. Here is the code:
public partial class Form1 : Form
{
List<Varianta> lvar = new List<Varianta>();
int contor = 0;
public Form1()
{
InitializeComponent();
}
private void cmbMaxim_SelectedIndexChanged(object sender, EventArgs e)
{
int[] vgen = new int[6];
int vmax = Convert.ToInt32(cmbMaxim.Text);
for (int i0 = 1; i0 < vmax - 4; i0++)
for (int i1 = i0 + 1; i1 < vmax - 3; i1++)
for (int i2 = i1 + 1; i2 < vmax - 2; i2++)
for (int i3 = i2 + 1; i3 < vmax - 1; i3++)
for (int i4 = i3 + 1; i4 < vmax; i4++)
for (int i5 = i4 + 1; i5 < vmax + 1; i5++)
{
Varianta var = new Varianta();
vgen[0] = i0;
vgen[1] = i1;
vgen[2] = i2;
vgen[3] = i3;
vgen[4] = i4;
vgen[5] = i5;
contor++;
var.Var = vgen;
var.Index = contor;
lvar.Add(var);
}
}
}
Class Varianta is:
class Varianta
{
int[] var = new int[6];
int index;
int scor=0;
int eliminate=0;
public int Scor
{
get
{
return scor;
}
set
{
scor = value;
}
}
public int Index
{
get
{
return index;
}
set
{
index = value;
}
}
public int [] Var
{
get
{
return var;
}
set
{
var = value;
}
}
}
What is wrong?
Varalready has an array allocated, why are you overwritting it with something that is shared across all of the loops? Instead why not justvar.Var[0] = i0;, etc.?vgento the innermost loop. All you objects points to the same array.varalready inVarianta, I would personally makeVar'ssetto be private (i.e. you can't assign a new array, but you can access and set the values in the array).