Nullable type to value type in C#

This short article answers the question “how to convert nullable type to value type in C#”.

As far as you know, a value type can’t be assigned a null value, but sometimes we need to do it. For example when we are working with a database and the value we receive could be null.

It’s very easy to declare using Nullable<T>:

// Nullable declaration using question mark 
int? catId = null;
bool? isShorthair = null;
// Equivalent declaration using
Nullable<T> Nullable<int> dogId;
Nullable<bool> hasTail;

But how to convert, for example, Nullable<int> to int? As far as all nullable types have two properties: Value and HasValue, we can do the following:

int intCatId; if (catId.HasValue) 
intCatId = catId.Value;
intCatId = default(int);

Or in a shorter way:

intCatId = catId == null ? default(int) : v1; // We also can use null-coalescing operator (??) 
intCatId = catId ?? default(int);

But, since .NET 4.0 there is another more convenient and readable way. We can use null-safe getter:

intCatId = catId.GetValueOrDefaul();

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store