0

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?

4
  • 1
    List<T> doesn't have a Length property. Did you mean Count? Could you provide a minimal reproducible example and test the code for yourself first? Note that if myList is null, myList?.Count is null, which isn't equal to 0 - so you'd then end up with an exception. Commented Apr 12, 2018 at 10:54
  • 3
    myListProcessingMethod() can be boiled down to return myList.Any(); essentially. Commented Apr 12, 2018 at 10:59
  • I edit my question: Actually I have an 2 dimensional array of Object in first method arrgument Commented Apr 12, 2018 at 11:01
  • Why don't you just say if (myList?.Any(x => x.satisfiesCondition()) ?? false) { a = 5; }? Commented Apr 12, 2018 at 11:11

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

maybe he doesn't use the System.Collection.Generic.List. You're missing the point @Badiparmagi
@Andrew is it possible to join this two if statement as myListProcessingMethod argument?
@ElConrado you can use && instead of 2 ifs... or what do you mean? You can also make myListProcessingMethod an extension method so you can chain it at the end, after ToList.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.