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.
thing isn't null. Since structs can't be null, so Nullable<int> can't be null.
The thing is... it is just compiler magic. You think it is null. In fact, the HasValue is just set to false.
If you call GetValueOrDefault it checks if HasValue is true or false:
public T GetValueOrDefault(T defaultValue) { return HasValue ? value : defaultValue; }
GetValueOrDefault () prevents errors that may occur because of null. Returns 0 if the incoming data is null.
int ageValue = age.GetValueOrDefault(); // if age==null
The value of ageValue will be zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With