Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert C# nullable int to int

Tags:

c#

nullable

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?

like image 569
KentZhou Avatar asked May 13 '11 16:05

KentZhou


People also ask

How do you convert Celsius to Fahrenheit easy?

To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32.

What is the formula to C?

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.

How do you convert numbers to Celsius?

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.


4 Answers

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 image 161
KeithS Avatar answered Oct 11 '22 09:10

KeithS


Like this,

if(v1.HasValue)
   v2=v1.Value
like image 42
Srinivas Reddy Thatiparthy Avatar answered Oct 11 '22 07:10

Srinivas Reddy Thatiparthy


You can use the Value property for assignment.

v2 = v1.Value;
like image 122
e36M3 Avatar answered Oct 11 '22 07:10

e36M3


All you need is..

v2= v1.GetValueOrDefault();
like image 95
thestar Avatar answered Oct 11 '22 09:10

thestar