1

I saw a code with & in linq condition

 var highestApplicationStatus = (from status in ctx.ApplicationStatuses.Where(o => o.ApplicationId == Application.ApplicationId & o.IsDeleted == false & o.StatusDate != null).OrderByDescending(o => o.ApplicationStatusType.DisplayOrder) select status).FirstOrDefault();

I rewrote it using &&

  var highestApplicationStatus = (from status in ctx.ApplicationStatuses.Where(o => o.ApplicationId == Application.ApplicationId && o.IsDeleted == false && o.StatusDate != null).OrderByDescending(o => o.ApplicationStatusType.DisplayOrder) select status).FirstOrDefault();

There has been a bug while released and i have been asked about this change. My understanding was that && is used for Logical And where as & is for bit wise operation . One team member was suggesting that & / && are same in Linq Environment. Can someone explain the difference

makdu
  • 908
  • 2
  • 13
  • 26
  • 4
    Use `&&`. Whomever is defending use of `&` in this context is wrong. – mjwills Oct 30 '19 at 02:52
  • Yes, some providers *may* treat them as equivalent (e.g. when generating SQL). Nonetheless, you should use `&&`. – mjwills Oct 30 '19 at 02:53
  • An aside comment: never ever change any existing code that looks wrong. – Antediluvian Oct 30 '19 at 03:04
  • @JimG., I read through it, but the question is specific to linq query – makdu Oct 30 '19 at 03:04
  • 2
    @Antediluvian Well, _verify_ that it’s wrong first, *then* tidy it up. And test it in a staging environment first! – Dai Oct 30 '19 at 03:07
  • You're asking 2 questions: 1. Should `&&` or `&` be used? 2. Should I have changed the code if I think there is a bug in it? The may have different answers. In your case the answers may be true and false respectively. – tymtam Oct 30 '19 at 03:11
  • @Antediluvian The counter argument is that this code is likely to be copied and reused elsewhere. Spurring further (pointless) discussion about the differences between `&` and `&&` etc. With 99.9% certainty, `&&` was meant (i.e. should have been used) here. _Obviously you still need to test it, to be 100% sure._ – mjwills Oct 30 '19 at 03:11
  • In this context, `&&` just causes the logic to short-circuit on the first false evaluation. With `&`, it actually evaluates all expressions. In order for your fix to have broken something, there would need to be some critical logic occurring in the `IsDeleted` and/or `StatusDate` properties that would have been prevented by the short circuit operator. – oscilatingcretin Oct 30 '19 at 03:12
  • `With '&', it actually evaluates all expressions` @oscilatingcretin That is true for LINQ to Objects. It is not _necessarily_ true for all LINQ query providers. In practical terms, `&` is only useful in this general context if you have code in your projection with side effects (and if that is the case, well you have bigger issues). – mjwills Oct 30 '19 at 03:13

0 Answers0