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;
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();