Search code examples
checkboxlinqpadlinqpad7

Linqpad checkbox update an instance problem


I want to let the user check a list of checkboxes, and after that when clicking a button act on what was checked. I defined an event for each check box, when its check is changed, the instance for which it was created will be updated:

void Main()
{
    var fooList = new[] { 1, 2, 3 }.Select(num => new Foo { Id = num });

    fooList.Select(foo => new CheckBox(foo.Id.ToString(), onClick: cb => foo.Status = cb.Checked)).Dump();
    new Button("Show fooList updated", _ => fooList.Dump()).Dump(); //always all Status is false!
}

class Foo
{
    public int Id { get; set; }

    private bool _status = false;

    public bool Status
    {
        get => _status;
        set
        {
            _status = value;
            value.Dump("now successed change value"); //printed!
        }
    }
}

The strange result is that the Status values are always false!

enter image description here


Solution

  • I found the problem...

    The fooList is IEnumerable, so anyone who accesses it creates a completely new copy...

    Adding ToArray() (In line 3) solved the mystery.