2

I have this function has two requirements

  1. return only orders that have an OrderDate value other than null

  2. return orders that were placed in the year specified in the parameter year or later

Which WHERE statement meets the requirements? And why?

static IQueryable<Order> lookUp (int year)
{
    using (DataClasses1DataContext  d = new DataClasses1DataContext())
    {
        var orders = from order in d.Orders
 This line ==>      where order.OrderDate.HasValue && order.OrderDate.Value.Year >=year
        OR ==>      where order.OrderDate.Value!=null && order.OrderDate.Value.Year >=year
                    select order;
        return orders.ToList();
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Fadi Alkadi
  • 781
  • 4
  • 12
  • 22
  • Did you mean that the second line has `order.OrderDate.Value!=null` or should have that read `order.OrderDate!=null`? – Enigmativity Jun 01 '14 at 22:26

1 Answers1

4

HasValue will tell you whether it is null or not. Value will get the non-null value, or throw an exception if it's null. Since you do not want to throw in the case of a null value, you shouldn't use the second.

Using != null (on the nullable itself, not on the .Value of it) is equivalent to using HasValue (the compiler generates a HasValue call). The following are both valid, then, and which to use is a stylistic choice.

where order.OrderDate.HasValue && ...
where order.OrderDate != null && ...
Tim S.
  • 55,448
  • 7
  • 96
  • 122