Failed to update shared list content

I have a simple class that has a boolean field:

public struct Foo { bool isAvailable; }

Now I have a foos list:

List < Foo >  list = new List< Foo >();

Later, I list each foo in the list and try to update its isAvailable field:

foreach(Foo foo in list) {
    foo.isAvailable = true; 
}

But the code above never updates the list. What am I doing wrong here and what is his remedy.

+3
source share
3 answers

This is because it Foois a mutable structure.

When you retrieve a value from a list, it makes a copy - because it behaves like value types. You change the copy, leaving the original value unchanged.

Suggestions:

  • You should probably use a class
  • . , , , , , .

, - , . ... .


, Foo

. , , , :

using System.Collections.Generic;

public class Foo
{
    public bool IsAvailable { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return Name + ": " + IsAvailable;
    }
}

class Test
{
    static void Main()
    {
        List<Foo> list = new List<Foo>()
        {
            new Foo { Name = "First", IsAvailable = true },
            new Foo { Name = "Second", IsAvailable = false },
            new Foo { Name = "Third", IsAvailable = false },
        };

        Console.WriteLine("Before:");
        list.ForEach(Console.WriteLine);
        Console.WriteLine();

        foreach (Foo foo in list)
        {
            foo.IsAvailable = true;
        }

        Console.WriteLine("After:");
        list.ForEach(Console.WriteLine);
    }
}

, , , , , .

+7

Foo, . , , , , .

, :

  • . foreach.

+2

When you populate the list, you need to create a new istance for each Foo class.

List list = new List (); Foo foo = new Foo ();

foo.isAvailable = false; list.Add (Foo);

foo = new Foo (); list.Add (Foo);

foo = new Foo (); list.Add (Foo);

if you fill out this path:

List list = new List (); Foo foo = new Foo (); list.Add (Foo); list.Add (Foo); list.Add (Foo);

you are referring to the same memory location on the stack for each object.

0
source

Source: https://habr.com/ru/post/1778314/


All Articles