Is there any way to convert this ?
public int? intVal ;
public double? dblVal ;
How I am working now
if(dblVal==null)
intVal =null;
else
intVal = Convert.ToInt32(dblVal);
Any alternative way ? Thanks in advance .
Just cast:
intVal = (int?) dblVal;
This will already result in a null
value if dblVal
is null. Note that unlike Convert.ToInt32(double)
, this does not result in an exception if dblVal
is outside the range of int
. If that's a concern, you should work out exactly what you want to achieve.
From the C# 5 spec, section 6.2.3:
Explicit nullable conversions permit predefined explicit conversions that operate on non-nullable value types to also be used with nullable forms of those types. For each of the predefined explicit conversions that convert from a non-nullable value type S to a non-nullable value type T (§6.1.1, §6.1.2, §6.1.3, §6.2.1, and §6.2.2), the following nullable conversions exist:
- An explicit conversion from S? to T?.
- An explicit conversion from S to T?.
- An explicit conversion from S? to T.
Evaluation of a nullable conversion based on an underlying conversion from S to T proceeds as follows:
- If the nullable conversion is from S? to T?:
- If the source value is null (HasValue property is false), the result is the null value of type T?.
- Otherwise, the conversion is evaluated as an unwrapping from S? to S, followed by the underlying conversion from S to T, followed by a wrapping from T to T?.
- ...
See more on this question at Stackoverflow