tags:

views:

57

answers:

2

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

+1  A: 

What it boils down to is that the nullable types are a rather leaky abstraction. They work fine when assigning a DateTime to a DateTime?, but with comparisons, things get tricky since System.Nullable doesn't really know how to deal with them.

There is no implicit conversion between the DateTime? and the DateTime, so what you need to do is actually get a real DateTime value out of the nullable to compare against. The easiest way to do that is to use the GetValueOrDefault() method from the nullable DateTime. This will give you the value if it is not null, and the default DateTime (which is DateTime.MinValue, I believe) if it is null.

ckramer
+1  A: 

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?))
Quartermeister