C# .Net

Structs and Lists

1 min read
Simon Coope
Simon Coope

Table of Contents

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 = &quot;One&quot;},
    new TestObject {Id = 2, Name = &quot;Two&quot;},
    new TestObject {Id = 3, Name = &quot;Three&quot;},
    new TestObject {Id = 4, Name = &quot;Four&quot;},
    new TestObject {Id = 5, Name = &quot;Five&quot;}

for (int i = 0; i &lt; list.Count; i++)
    var item = list[i];
    item.Name = &quot;Changed&quot;;

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

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.