1

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.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
SuperMinefudge
  • 301
  • 3
  • 11
  • 3
    Any other "syntatic sugar" method will end up in looping through all items. You can use LINQ ro you can use `Array.ConvertAll` – Fabio Jan 01 '17 at 21:20
  • @Fabio I think OP is indeed asking for a syntactic sugar. Why don't you post the `ConvertAll` method based answer which will be the best solution for arrays (not like the current answers which are more general, but also less efficient). – Ivan Stoev Jan 01 '17 at 21:29

3 Answers3

8

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);
Fabio
  • 31,528
  • 4
  • 33
  • 72
  • Of course OP has chosen the shortest to type, although it's the worse from the three posted (box + unbox). +1 – Ivan Stoev Jan 01 '17 at 21:44
  • I was just about to ask you how to do it with the Array.Convert All and yes i really forgot about boxing and unboxing thank you – SuperMinefudge Jan 01 '17 at 21:49
  • btw isnt doing this: "new int?(value)"boxing aswell? – SuperMinefudge Jan 01 '17 at 21:51
  • @SuperMinefudge No. Boxing is when you convert `int` to `object`. `Cast` is doing that because it operates on `IEnumerable` (note - not `IEnumerable`). So the equivalent of `Cast` is something like `arr.Select(x => (int?)(object)x)`. Btw, I'm glad you have changed your preference. – Ivan Stoev Jan 01 '17 at 21:55
7

I suggest using Linq:

 int?[] nullable_arr = arr
   .Select(item => new int?(item))
   .ToArray();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
5

You could use Cast from Linq

int?[] arrNull = arr.Cast<int?>().ToArray();
BrunoLM
  • 97,872
  • 84
  • 296
  • 452