5

For the life of me, I can't figure out why all the foos are not null. I'm assuming the .ForAll() should be executing before I call the .All() method, but it's not?

public class Foo
{
    public string Bar { get; set; }
}

static void Main(string[] args)
{
    var foos = new List<Foo> { new Foo(), new Foo(), new Foo() };
    var newFoos = foos
        .AsParallel()
        .Select(x =>
        {
            x.Bar = "";
            return x;
        });
    newFoos.ForAll(x => x = null);
    var allFoosAreNull = newFoos.All(x => x == null);
    Console.WriteLine(allFoosAreNull); // False ??
}
Brad M
  • 7,857
  • 1
  • 23
  • 40

1 Answers1

7

When you do this

newFoos.ForAll(x => x = null);

you are assigning null to x, which is the parameter of your lambda. x is local to the lambda. It is not a ref parameter, and assigning values to it has no effect outside of its body. Effectively, that line does nothing.

recursive
  • 83,943
  • 34
  • 151
  • 241
  • Even if I modify the body of the lambda to set the `Bar` property to another value, that value doesn't stick either. I'm still a bit perplexed; I'm under the assumption that `ForAll()` is iterating over the actual list. In other words, why would the lambda *not* be `ref`? – Brad M May 27 '15 at 00:12
  • Now that I think about it, this doesn't even have anything to do with PLINQ...it's the same behavior with `.ForEach()`. – Brad M May 27 '15 at 00:19