Null Coalesce returning value of first non null variable

1.4k views Asked by At

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?

4

There are 4 answers

0
Servy On

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.

0
Damian On

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);
1
CodingYoshi On

This is cleaner and it will skip the null values:

var total = votes.Sum();
1
Szörényi Ádám On
var total = votes.Sum();

It will count null values as zero.