Cannot modify the return value of ‘System.Collections.Generic.List.this[int]‘ because it is not a variable

I recently stumbled upon this compile time error while trying to change the value of a structure over iteration. The Compiler throws this error when returned structure is modified. The reason is that structures are value types and immutable. The returned structure will be a copy. And any change to the copy doesn’t reflect in the original structure hence the compiler prevents from doing this which is not intended.

For instance, the following code won’t compile. The compiler will throw
Cannot modify the return value of ‘System.Collections.Generic.List.this[int]’ because it is not a variable

public struct Person
{
    public string Name;
}

public class StringUtil
{
    public void ToUpper(List<Person> persons)
    {
        for (int i = 0; i < persons.Count; i++)
	{
            persons[i].Name = persons[i].Name.ToUpper();
        }
     }
}

The solution requires not changing the value and creating a new structure with new values.

public class StringUtil
{
    public void ToUpper(List<Person> persons)
    {
        for (int i = 0; i < persons.Count; i++)
	{
            persons[i] = new Person { Name = persons[i].Name.ToUpper() };
        }
     }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s