I have following methods:
float myMethod(MyObject[][] myList)
{
float a = 0;
if (myListProcessingMethod(myList?.Where(x => x.mySatisfiedCondition()).ToList()))
{
a = 5;
}
return a;
}
bool myListProcessingMethod(List<MyObject[]> myList)
{
bool isSuccess = false;
if (myList.Any())
{
isSuccess = true;
}
return isSuccess;
}
I consider this condition:
if (myListProcessingMethod(myList?.Where(x => x.mySatisfiedCondition()).ToList()))
I refactor my condition to:
if (myList?.Length != 0)
{
if (myListProcessingMethod(myList.Where(x => x.mySatisfiedCondition()).ToList()))
{
a = 5;
}
}
Is this two conditions are equivalent? What is equivalent condition to first NullConditionOperator in traditional way? What is equivalent condition to second traditional checking using NullConditionalOperator?
The statement below can crash. If myList
is null, myList?.Length
will be null and myList?.Length != 0
will be true. That means myList.Where
may crash with a null reference exception.
if (myList?.Length != 0)
{
if (myListProcessingMethod(myList.Where(x => x.mySatisfiedCondition()).ToList()))
{
a = 5;
}
}
you probably want
if (myList?.Length > 0)
...
which will evaluate to true only if the list is not null and its Length is grater than 0.