Search code examples
c#arraysnullablenon-nullable

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


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.


Solution

  • 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);