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
?
To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32.
The relationship between Fahrenheit and Celsius is expressed with the formula, °C = (°F - 32) × 5/9; where C represents the value in Celsius and F represents the value in Fahrenheit.
The temperature conversion is easy to do: Take the °F temperature and subtract 32. Multiply this number by 5. Divide this number by 9 to obtain your answer in °C.
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();
Like this,
if(v1.HasValue)
v2=v1.Value
You can use the Value property for assignment.
v2 = v1.Value;
All you need is..
v2= v1.GetValueOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With