Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant way to add nullable ints?

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();         }     } } 
like image 235
Edward Tanguay Avatar asked Aug 30 '10 10:08

Edward Tanguay


People also ask

How do you create a nullable integer?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

Can integer be nullable?

No, but int[] can be. Show activity on this post.

Can nullable be null C#?

Nullable is a term in C# that allows an extra value null to be owned by a form. We will learn in this article how to work with Nullable types in C#. In C#, We have majorly two types of data types Value and Reference type. We can not assign a null value directly to the Value data type.

How do you create a nullable value?

If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl + 0 .


2 Answers

var nums = new int?[] {1, null, 3}; var total = nums.Sum(); 

This relies on the IEnumerable<Nullable<Int32>>overload of the Enumerable.Sum Method, which behaves as you would expect.

If you have a default-value that is not equal to zero, you can do:

var total = nums.Sum(i => i.GetValueOrDefault(myDefaultValue)); 

or the shorthand:

var total = nums.Sum(i => i ?? myDefaultValue);

like image 57
Ani Avatar answered Sep 21 '22 07:09

Ani


total += sum1.GetValueOrDefault(); 

etc.

like image 42
Albin Sunnanbo Avatar answered Sep 24 '22 07:09

Albin Sunnanbo