I want to say that my code works correctly but i don’t know why it is working like that. So to make it clear, here is my code:
List<NewsFlash> newsfl = tsm.getNewsFlashes();
foreach (NewsFlash item in newsfl)
{
item.smartform.dtDate = item.smartform.dtDate.ToShortDateString();
}
//Get all the newsFlash items and bind to the repeater
rptNewsFlash.DataSource = newsfl;
rptNewsFlash.DataBind();
Like you can see, I am looping the list newsfl and I am editing item.smartform.dtDate. What is weird for me is, when I edit item.smartform.dtDate, then the property dtDate in the list newsfl is also changed. This is what I want, but it is kind of weird I think, because item within the foreach loop has nothing to do with the list newsfl?
Hope you understand my question.
Thanks
Each
itemin theforeachis just a reference to the item at a specific index withinnewsfl– so when your loop is done, you’ve updated all theitem‘s in the list, and those items hang onto those changes. This makes sense because each item is not a copy of the original, it is the original.So, imagine
itemandnewsfl[n]as two doors to the same room, you end up in the same place – and it doesn’t matter which door I arrive through, if I start moving furniture around, it is also moved for anyone who comes in through either door.On another note, if this didn’t happen, then what would you expect to happen? Since you make changes to
item, surely you want to keep them?