How to convert C# nullable int to int
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
?
Solution 1:
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.Value;
...which is in turn syntax sugar for an if/else:
if(v1==null)
v2 = default(int);
else
v2 = v1.Value;
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();
Solution 2:
Like this,
if(v1.HasValue)
v2=v1.Value
Solution 3:
You can use the Value property for assignment.
v2 = v1.Value;
Solution 4:
All you need is..
v2= v1.GetValueOrDefault();