I am trying to optimize the code using SonarQube
List<string> itemList = serviceObject.GetItems();
I tried to validate the list with the below code
if(itemList != null && itemList.Any()
{
//Some operations
}
when above code executed I am getting Sonarqube error remove this expression which always evaluates to "true" So I refactor the code as
if(itemList == null || !itemList.Any())
return;
//Some Operations
when above code executed I am getting Sonarqube error remove this expression which always evaluates to "false"
Could anyone let me know what is wrong here?
You can shorten this to
if (itemList?.Count >0)
{
...
}
or
if (itemList?.Any() ==true)
{
...
}
?.
is one of the Null conditional operators (the other is ?[]
), the Elvis operator
for short, that allows you to access potentially null variables without throwing. The result of the entire expression after the Elvis operator is nullable and returns null
if the variable is null.
This means that itemList?.Count
returns an Nullable<int>
, and itemList?.Any()
a Nullable<bool>
. Nullable<T>
defines relational operators between itself and its base type T but can't be used as T without an explicit cast. That's why (itemList?.Any() ==true)
is needed.
If you use Nullable Reference Types though, itemList
can't be null, so a simple comparison would be enough:
if (itemList.Count >0)
{
...
}
If you enable Nullable Reference Types by setting #nullable enable
in a source file or <Nullable>enable</Nullable>
in the csproj
file, the compiler ensures that all variables, fields and methods that return reference types are not null, forcing you to either fix the problem or explicitly specify that a variable is nullable.
With NRTs enabled this line :
List<string> itemList = serviceObject.GetItems();
Would only compile without warnings if GetItems
never returned a null. If the compiler doubts this, it would issue a warning advising you to either fix the problem or explicitly declare itemList
as nullable with :
List<string>? itemList = serviceObject.GetItems();