I\'m using a linq query to output an int array. But I need to pass this into a method that only accepts int?[].
So after searching on ways to convert int[] to int?[] I
This extension method, ToArrayOrNull
, does not change the type of the contents. seq
is an IEnumerable
of T
. result
is an array of T
(which you sometimes return as null
, but that's still an array of T
.
If you really want to convert an IEnumerable
to an IEnumerable
(or an array of T?
), you should put some constraints on the type parameter (it should be struct
, meaning a value type, one that cannot be null), and convert each item instead of the whole result, something like:
public static T?[] ToArrayOfNullable(this IEnumerable seq)
where T : struct
{
return seq.Select(val => (T?)val).ToArray();
}
Although I would return an IEnumerable
here and convert to an array later, to keep this method simple.