-1

I'm trying to add several integers together using NULL Coalesce, in which at least 2 of the integers may be NULL, in that case, assign 0 to such integers and then add.

var total = votes[0].Value ?? 0 + votes[1].Value ?? 0 + votes[2].Value ?? 0 + votes[3].Value ?? 0;

total returns the value of votes[0].Value instead of addition of all four variables.

Is there a way I can get the total of all the integers?

hello
  • 1,168
  • 4
  • 24
  • 59
  • Are you sure the array has the values you think it does? If you break on it, and inspect their values... – rory.ap Dec 30 '16 at 22:09
  • Yes it does when I step through in debugger. – hello Dec 30 '16 at 22:09
  • 3
    Possible duplicate of [What is the operator precedence of C# null-coalescing (??) operator?](http://stackoverflow.com/questions/511093/what-is-the-operator-precedence-of-c-sharp-null-coalescing-operator) – Paul Roub Dec 30 '16 at 22:10

4 Answers4

4
var total = votes.Sum();

It will count null values as zero.

Szörényi Ádám
  • 1,223
  • 13
  • 17
  • 1
    "null values as zero": while this is effectively true for `Sum`, it is more general to say it skips null values. That way, it applies to `Average` and others, too. (But, not `Count` of course.) – Tom Blodget Dec 31 '16 at 00:05
1

That code is equivalent to:

var total = votes[0].Value ?? (0 + votes[1].Value ?? (0 + votes[2].Value ?? (0 + votes[3].Value ?? 0)));

So it should be rather apparent now why it returns votes[0].Value rather than the sum of all of the non-null values.

Servy
  • 202,030
  • 26
  • 332
  • 449
1

If votes is an array of nullable integers you can write:

var votes = new int?[] {1, 2, 3, 4};
var total = (votes[0] ?? 0) + (votes[1] ?? 0) + (votes[2] ?? 0) + (votes[3] ?? 0);
Damian
  • 2,752
  • 1
  • 29
  • 28
0

This is cleaner and it will skip the null values:

var total = votes.Sum();
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64