user3089631
user3089631

Reputation: 169

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?[]

Upvotes: 5

Views: 3314

Answers (2)

James
James

Reputation: 82136

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

sample.IdValues = sampleDetails.Select(x => x.Id)
                               .Cast<int?>()
                               .ToArray();

Upvotes: 1

Adam Houldsworth
Adam Houldsworth

Reputation: 64517

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(); 

Upvotes: 6

Related Questions