Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type int[] to int?[]

In my sample class it contain IdValues that is int?[]. The values is come from the other class that has an Id as a key field.

//Database class
public class SampleValues // this is a entity that i want to collect the deatil id
{
    public int Id { get; set; }
    public int?[] SampleDetailIdValue { get; set; }
}

public class SampleDetailValues // this is the detail entity
{
    public int Id { get; set; }
}


// The error code
if (sampleDetails.Count > 0)
{
    sample.IdValues = sampleDetails.Select(s => s.Id).ToArray(); // << The error occurred this line.
}

The error is Cannot implicitly convert type int[] to int?[]

like image 680
user3089631 Avatar asked Dec 11 '13 09:12

user3089631


2 Answers

Cast in your projection:

sample.IdValues = sampleDetails.Select(s => (int?)s.Id).ToArray(); 

You were projecting an int, calling ToArray giving you an int[], so simply project an int? instead.

There is alternatively the Cast extension method:

sample.IdValues = sampleDetails
    .Select(s => s.Id) 
    .Cast<int?>()
    .ToArray(); 
like image 120
Adam Houldsworth Avatar answered Sep 30 '22 02:09

Adam Houldsworth


It can't be implicitly cast, but an explicit cast should work

sample.IdValues = sampleDetails.Select(x => x.Id)
                               .Cast<int?>()
                               .ToArray();
like image 41
James Avatar answered Sep 30 '22 01:09

James