Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does GetValueOrDefault work?

Tags:

c#

nullable

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.

like image 226
Ian Newson Avatar asked Apr 14 '15 11:04

Ian Newson


2 Answers

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; } 
like image 81
Patrick Hofman Avatar answered Oct 07 '22 19:10

Patrick Hofman


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.

like image 30
Murat Kara Avatar answered Oct 07 '22 19:10

Murat Kara