I had a bit of an interesting time with some very basic code today. I was iterating over a collection and updating properties of items in the collection. But when out of the loop the settings hadn't been maintained. So as an example, the code in question looked similar to the following:

var list = new List<TestObject>()
{
    new TestObject {Id = 1, Name = "One"},
    new TestObject {Id = 2, Name = "Two"},
    new TestObject {Id = 3, Name = "Three"},
    new TestObject {Id = 4, Name = "Four"},
    new TestObject {Id = 5, Name = "Five"}
};

for (int i = 0; i < list.Count; i++)
{
    var item = list[i];
    item.Name = "Changed";
}

// Check how many items in the list have the name of "Changed"
var changedCount = list.Where(i => i.Name == "Changed");

My problem was that the 'changedCount' variable was always 0! How could that be when I was setting the value in the for loop? Well, when we look at the TestObject definition it should be obvious...

public struct TestObject
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Yes, TestObject is a struct. So, as we all know a struct is a value type and a class is a reference type. As a really basic overview, value types contain their values, whereas reference types contain a pointer to the value. So when iterating through the list in the for loop and we set the item variable, we're setting it to a copy of the struct. Therefore, any changes to the copy of the struct won't be maintained on the struct in the list.