2

I am having below code and wondering why else part is unreachable as per resharper.

private bool SomeMEthod(some parameter)
{
    bool status = false; 
    var someCollection = _entity.CustomerPaymentStatus.Where(record => record.CustomerPaymentId == paymentId && record.CurrentRecord == true);
    if (someCollection != null)
    {
        var receivedPayment = someCollection.FirstOrDefault();
        /*some code to save data into DB*/
        status = true;
    }
    else
    {
        //Some code here to log failure scenario

        //here Resharper giving me warning
        //code is heuristically unreachable
    }
    return status;
}

I have checked couple of post but not clear like Code is heuristically unreachable

Any Thought please.

Community
  • 1
  • 1
LifeOfPi
  • 625
  • 5
  • 19
  • 4
    `Where` should never return `null` but might return an empty sequence, so your `if` condition will always evaluate to `true`. – Lee Jun 20 '16 at 09:48

3 Answers3

5

.Where() never returns null, but always returns an IEnumerable<T> (or IQueryable<T>. The enumerable might have 0 items, but it's still a non-null enumerable.

knittl
  • 246,190
  • 53
  • 318
  • 364
  • And if `_entity.CustomerPaymentStatus` is null, then an exception will be thrown and `else` won't be reached either – Kevin Gosse Jun 20 '16 at 09:50
  • @KooKiz: yes, of course. But a `NullReferenceException` is a completely different problem ;) – knittl Jun 20 '16 at 09:51
2

The Linq Where query will return an empty IEnumerable if no matching records are found, so it is highly unlikly that someCollection will ever be null - although ReSharper does not seem to be completly sure about it.

Also see MSDN Where

ZoolWay
  • 5,411
  • 6
  • 42
  • 76
0

Assuming _entity is a DbContext, then Where always returns an IQueryable object.

 IQueryable<T> someCollection = _entity.CustomerPaymentStatus.Where(...);

That IQueryable object is never null (otherwise you wouldn't be able to query it).

Testing that object for null doe not execute the query. So

 if (someCollection != null)

is the same as

 if (true)