Share via


Convert array to nullable array

Question

Thursday, January 4, 2007 12:44 PM

Hi,

The following code does'nt compil :

int[] tab = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int?[] nulltab = (int?[])tab;
Cannot convert from 'int[]' to 'int?[]

How I can cast my array ?

Thanx

All replies (5)

Friday, January 5, 2007 1:38 AM âś…Answered | 1 vote

how about:

 

static T?[] ConvertArray<T>(T[] array) where T : struct

{

T?[] nullableArray = new T?[array.Length];

for (int i = 0; i < array.Length; i++)

nullableArray[ i ] = array[ i ];

return nullableArray;

}


Thursday, January 4, 2007 1:17 PM

int and int? are assignment compatible but not blittable.  Workarounds are to make "tab" of type int?[] or to create nulltab and copy the tab elements.  Moved to C# Language forum.


Thursday, January 4, 2007 1:46 PM

I tried to create the following function but that doesn't works to

static T[] ConvertArray<T, V>(V[] array)

{

T[] nullableArray = new T[array.Length];

for (int i = 0; i < array.Length; i++)

nullableArray[ i] = (T)array[ i];

return nullableArray;

}

=>Cannot convert 'V' to 'T'

Can you help me ?

 

 

 


Friday, January 5, 2007 10:21 AM

int[] tab = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int?[] nulltab = (int?[])tab;

Why do you need a "nullable" array? Arrays are already nullable.

You can do:

int[] tab = null;

if (tab == null)
    ...

Etc.


Friday, August 5, 2016 11:54 AM

int?[] array = new int?[5];