Home > Net >  Checking if a List is Null before getting Count results in -> Cannot implicitly convert type 
Checking if a List is Null before getting Count results in -> Cannot implicitly convert type 

Time:04-01

I'm trying to find the number of items present in a list.In order to prevent the null exception.I'm using the ? operator to check whether myBenchmarkMappings is null before getting its count.

 int benchmarkAccountCount =portfolioWrapper.myBenchmarkMappings?.Count;

But this results in Cannot implicitly convert type 'int?' to 'int'. exception

What am i doing wrong ?

CodePudding user response:

This is because the ? operator will return the value or null. And you can't assign null to int.
You have two options. First is to mark the int as nullable. But in this case latter you will need to check if the int is null.

int? benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count;

if (benchmarkAccountCount == null) 
{
    // null handling
}

The second option, which I think is better, you can user the null-coalescing operator ?? and give the benchmarkAccountCount a default value in case the list is null.

int benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count ?? 0;

CodePudding user response:

When .myBenchmarkMappings is null, then .myBenchmarkMappings?.Count is also null. This means this code could possibly assign a null to an int, but an int can't store a null. Change the type to int? if you want to accommodate an int or null.

int? benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count;

CodePudding user response:

You can try to use ?: operator to check if list is null:

 int benchmarkAccountCount =portfolioWrapper.myBenchmarkMappings!=null ? portfolioWrapper.myBenchmarkMappings.Count:0;
  • Related