Can someone explain what is going on here? Howcome both these things are true?
[TestMethod]
public void WhatIsGoingOnHere()
{
List<int?> list = new List<int?> { 1, 2, 3, null, 5, 6 };
Assert.AreEqual(17, list.Sum());
int? singleSum = 1 + 2 + 3 + null + 5 + 6;
Assert.IsNull(singleSum);
}
Specifically, why does the Sum() method not return ‘null’? Or the singleSum not equal 17?
What you are seeing is the difference between using
Enumerable.Sumand actually adding the values yourself.The important thing here is the
nullis not zero. At first glance you would think thatsingleSumshould equal 17 but that would mean that we would have to assign different semantics tonullbased on the data type of the reference. The fact that this is anint?makes no difference –nullisnulland should never be semantically equal with the numeric constant0.The implementation of
Enumerable.Sumis designed to skip over any value that isnullin the sequence so that is why you are seeing the different behavior between the two tests. However the second test rightly returnsnullas the compiler is smart enough to know that adding anything tonullyieldsnull.Here is the implementation of
Enumerable.Sumthat accepts a parameter ofint?: