Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make int array Nullable?

Tags:

c#

.net

I have this code:

var contractsID = contracts.Select(x => x.Id);
int?[] contractsIDList = contractsID.ToArray();//for debug

In this line:

int?[] contractsIDList = contractsID.ToArray();//for debug

I get this error:

Can not implicitly convert type int[] to int

what i try to do is to make contractsIDList Nullable type.

How to make int array Nullable?

like image 717
Michael Avatar asked Oct 06 '15 13:10

Michael


3 Answers

The error you should get is:

Can not implicitly convert type int[] to int?[]

Thus you need to convert the values:

int?[] contractsIDList = contractsId.Cast<int?>().ToArray();//for debug
like image 113
stuartd Avatar answered Oct 23 '22 02:10

stuartd


Arrays are always reference types - so they're already nullable.

But i guess that you actually want to get an int?[] from an int[](because the Id is not nullable). You can use Array.ConvertAll:

int[] contractsID = contracts.Select(x => x.Id).ToArray();
int?[] contractsIDList = Array.ConvertAll(contractsID, i => (int?)i);

or cast it directly in the LINQ query:

int?[] contractsIDList = contracts.Select(x => (int?) x.Id).ToArray();
like image 34
Tim Schmelter Avatar answered Oct 23 '22 03:10

Tim Schmelter


The easiest way in your case is to get int? from the Select:

var contractsID = contracts.Select(x => (int?)x.Id);
int?[] contractsIDList = contractsID.ToArray();
like image 5
Jakub Lortz Avatar answered Oct 23 '22 02:10

Jakub Lortz