1

I have defined motorData class as below:

public class motorData
 {
     public int data0 { get; set; }
     public int data1 { get; set; }
     public int data2 { get; set; }
     public int data3 { get; set; } 
     public int data4 { get; set; }
     public int data5 { get; set; }
     public int data6 { get; set; }
     public int data7 { get; set; }
     public int data8 { get; set; }
 }

The class is used in a Button click event like this:

List<motorData> mtdlist = new List<motorData>();
motorData mtd = new motorData();

private void button2_Click_1(object sender, EventArgs e)
{   
    mtd.data0 = 1;
    mtdlist.Add(mtd);
    mtd.data0 = 2;
    mtdlist.Add(mtd);
    mtd.data0 = 3;
    mtdlist.Add(mtd);
    mtd.data0 = 4;
    mtdlist.Add(mtd);
    mtd.data0 = 5;
    mtdlist.Add(mtd);

}

After calling the event, I get the following results:

mtdlist[0].data0 = 5;  
mtdlist[1].data0 = 5;  
mtdlist[2].data0 = 5; 
mtdlist[3].data0 = 5;  
mtdlist[4].data0 = 5;

If I define motorData as structure, I get the correct results. So what am I missing?

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
Ali80
  • 6,333
  • 2
  • 43
  • 33
  • How do you want the output? – captainsac Jun 12 '14 at 12:30
  • possible duplicate of [What's the difference between struct and class in .Net?](http://stackoverflow.com/questions/13049/whats-the-difference-between-struct-and-class-in-net) – nvoigt Jun 12 '14 at 12:30

1 Answers1

1

You are assigning the value to the same Object ,You should create new Object each time.

List<motorData> mtdlist = new List<motorData>();

private void button2_Click_1(object sender, EventArgs e)
{  
    motorData mtd1 = new motorData();
    mtd1.data0 = 1;
    mtdlist.Add(mtd1);
    motorData mtd2 = new motorData();
    mtd2.data0 = 2;
    mtdlist.Add(mtd2);
    motorData mtd3 = new motorData();
    mtd3.data0 = 3;
    mtdlist.Add(mtd3);
    motorData mtd4 = new motorData();
    mtd4.data0 = 4;
    motorData mt5 = new motorData();
    mtdlist.Add(mtd4);
    mtd5.data0 = 5;
    mtdlist.Add(mtd5);

}

To know more about Structure vs Class

Community
  • 1
  • 1
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396