Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq DateTime expressions wont compare if only one is nullable

Tags:

c#

linq

I have been getting the following exception:

The binary operator GreaterThanOrEqual is not defined for the types 'System.Nullable`1[System.DateTime]' and 'System.DateTime'.

I am getting the left hand expression from a class property which is a nullable datetime variable and my right hand side is using

Expression.Constant(new Nullable<DateTime>(DateTime.Now))

However I still get the above exception despite explicitly setting the right hand expression to a nullable type

like image 317
Anthony Main Avatar asked Dec 02 '22 05:12

Anthony Main


1 Answers

Expression.Constant takes in an object, so in your code the parameter is being boxed. Boxing a nullable value actually boxes the underlying value (see Boxing Nullable Types), so Expression.Constant thinks the parameter is a DateTime instead of a DateTime?.

You can force the ConstantExpression to be a DateTime? by using the overload of Expression.Constant that takes in a Type:

Expression.Constant(DateTime.Now, typeof(DateTime?))
like image 122
Quartermeister Avatar answered Apr 10 '23 00:04

Quartermeister