1

I found this bug in my current project and then I reproduced in a very simple code, which I share here.

I'm using ReSharper 8.0.2 and Visual Studio 2013.

class Program
{
    static void Main(string[] args)
    {
        var orders = new List<Order> { new Order {ClientId = 10}, new Order()};
        var firstOrder = orders.FirstOrDefault();
        if ( firstOrder != null && firstOrder.ClientId.HasValue)
        {
            // In this line resharper suggests that t.ClientId.HasValue is always true. This is wrong.
            var ordersWithClient = orders.Where(t => t.ClientId.HasValue).ToList();   
        }
    }
}

class Order
{
    public int? ClientId { get; set; }
}
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47

1 Answers1

-1

Its because you already have a conditional statement that checks if the ClientId has value before before assigning it to a variable. Thus the expression is always true

Hemi81
  • 578
  • 2
  • 15
  • 34
  • 3
    The `if` statement is checking the `firstOrder`, but the actual code is dealing with the `orders` which contains an `Order` with a `null` `ClientId`. – juharr Sep 17 '15 at 16:52
  • Thats not what his code is validating. Its validating the first order which the `ClientId` has already been set. Why the expression is always true – Hemi81 Sep 17 '15 at 17:15
  • The `if` validates the first order, but Resharper is saying that `t => t.ClientId.HasValue` is always `true`, but that's not correct because `orders` contains one entry where it is in fact `false`. – juharr Sep 17 '15 at 17:17
  • ``t => t.ClientId.HasValue`` validates the first entry as does the `if` statement correct? – Hemi81 Sep 17 '15 at 17:28
  • No the `orders.Where` is going to iterate through all the items in `orders`. – juharr Sep 17 '15 at 17:54
  • yes correct, but that also includes that the first/default order as well. – Hemi81 Sep 17 '15 at 18:17