I need to add numerous variables of type nullable int. I used the null coalescing operator to get it down to one variable per line, but I have a feeling there is a more concise way to do this, e.g. can't I chain these statements together somehow, I've seen that before in other code.
using System;
namespace TestNullInts
{
class Program
{
static void Main(string[] args)
{
int? sum1 = 1;
int? sum2 = null;
int? sum3 = 3;
//int total = sum1 + sum2 + sum3;
//int total = sum1.Value + sum2.Value + sum3.Value;
int total = 0;
total = total + sum1 ?? total;
total = total + sum2 ?? total;
total = total + sum3 ?? total;
Console.WriteLine(total);
Console.ReadLine();
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…