This project has moved and is read-only. For the latest updates, please go here.

Using Nullable types possible?

Jul 25, 2014 at 2:19 PM
Edited Jul 25, 2014 at 2:44 PM
First of all, thanks for a really useful and powerful library!

I have a question regarding nullable types; is it possible to execute queries against such types, like in the example below?

The following code results in an exception:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Additional information: The binary operator Equal is not defined for the types 'System.Nullable'1 [System.Int32]' and 'System.Int32'.
using System;
using ExpressionEvaluator;

namespace TestingExpressions
    class Tester
        public void TestNullable()
            var test = new Test { Foo = 123 };

            var expression = new CompiledExpression("Foo == 123");
            var func = expression.ScopeCompile<Test>();
            var result = func(test);
            Console.WriteLine("Result: {0}", result);

    class Test
        public int? Foo { get; set; }
I realized the following expression can be used, but it is pretty awkward, especially with more complex expressions, and I would really like to be able to use the above form instead:
var expression = new CompiledExpression("Foo != null ? Foo.Value > 123 : false");
I guess the way to handle nullable types could be something like this:
Foo.HasValue ? Foo > 123 : default(int) > 123;
Jul 29, 2014 at 10:25 PM
Edited Jul 30, 2014 at 2:48 PM
I'm probably not handling type inference for nullable types well enough. I'll look into it. Supposedly I should be automatically casting between nullable types and their generic type, or null, depending on the situation.


Come to think of it, I may have it wrong. There may be a bit of compiler magic happening in the background when nullable types are in play. with the .Value property being used instead.
Jul 30, 2014 at 8:35 PM
Yes, if I remember correctly, it is indeed compiler magic that enables us to do this in C# (dunno about VB):
int? myInteger = 123;
if (myInteger == 123) 
   return true;
...and not have to compare with .Value
And I guess .NET LINQ/Expressions does not do this "magic" internally since it is language agnostic and probably do not want to "simulate" C# in this case.