I'm responsible for a LINQ provider which performs some runtime evaluation of C# code. As an example:
int? thing = null;
accessor.Product.Where(p => p.anInt == thing.GetValueOrDefault(-1))
Currently the above code doesn't work with my LINQ provider due to thing
being null.
While I've been working with C# for a long time, I don't know how GetValueOrDefault is implemented and therefore how I should resolve this.
So my question is: how does GetValueOrDefault
work in the case that the instance on which it is called is null? Why isn't a NullReferenceException
thrown?
A follow on question: how should I go about replicating a call to GetValueOrDefault
using reflection, given that I need to handle null values.
Nullable<>
struct is special. Being a struct means it can not really benull
, but the language allows you to set it tonull
which just creates an instance withHasValue
set to false.GetValueOrDefault
is likely not working here because you are using EF (or some other query provider) that doesn't know how to translate it to SQL. – Europa