Saturday, November 22, 2014

Filled in List - From Class

Be very careful when you filling up the List. The output and how it behave.
I made a mistake that I hope will not made it again.
The part in purple colour is the outcome of the code when the debugger stop at that specific line of code.

List<Item> ar = new List<Item>{};
ar is empty. If you now access ar[0]Id, you will hit error.
           
ar.Add(new Item() { Id = 1, Name = "User1" });
If you now access: ar[0].Id = 1
           
ar.Add(new Item() { Id = 2, Name = "User2" });
If you now access: ar[0].Id = 1, ar[1].Id = 2

 
Item item = new Item(){Id = 3 , Name = "User3"};
ar.Add(item);
If you now access: ar[0].Id = 1, ar[1].Id = 2, ar[2].Id = 3

item.Id = 4;
item.Name = "User4";
ar.Add(item); 
If you now access: ar[0].Id = 1, ar[1].Id = 2, ar[2].Id = 4, ar[3].Id = 4

No comments:

Post a Comment