How to convert C# nullable int to int

KentZhou picture KentZhou · May 13, 2011 · Viewed 421.6k times · Source

How do I convert a nullable int to an int? Suppose I have 2 type of int as below:

int? v1;  
int v2; 

I want to assign v1's value to v2. v2 = v1; will cause an error. How do I convert v1 to v2?

Answer

KeithS picture KeithS · May 13, 2011

The other answers so far are all correct; I just wanted to add one more that's slightly cleaner:

v2 = v1 ?? default(int);

Any Nullable<T> is implicitly convertible to its T, PROVIDED that the entire expression being evaluated can never result in a null assignment to a ValueType. So, the null-coalescing operator ?? is just syntax sugar for the ternary operator:

v2 = v1 == null ? default(int) : v1;

...which is in turn syntax sugar for an if/else:

if(v1==null)
   v2 = default(int);
else
   v2 = v1;

Also, as of .NET 4.0, Nullable<T> has a "GetValueOrDefault()" method, which is a null-safe getter that basically performs the null-coalescing shown above, so this works too:

v2 = v1.GetValueOrDefault();