How to convert an int array to a nullable int array?

5.2k views Asked by At

Let's say I have an array containing x members and I want to create another array with the same Length (x) and the same integer values:

int[] arr = new int[x];
int?[] nullable_arr = arr;

And I can't do this:

int?[] arr = new int[x];

Is there an explicit conversion to a nullable type array or something I am not aware of?

Yes, I could simply convert each value in a loop but I'm asking if there is already an easy short way of doing this.

3

There are 3 answers

4
Fabio On BEST ANSWER

Another aproach by using Array.ConvertAll method

var values = new[] {1, 2, 3, 4};
var nullableValues = Array.ConvertAll(ints, value => new int?(value));

Or with providing generic types explicitly

var nullableValues = Array.ConvertAll<int, int?>(ints, value => value);
0
Dmitry Bychenko On

I suggest using Linq:

 int?[] nullable_arr = arr
   .Select(item => new int?(item))
   .ToArray();
0
BrunoLM On

You could use Cast from Linq

int?[] arrNull = arr.Cast<int?>().ToArray();