It a very simple question - convert a type long variable to a Nullable int type (int?). (see example below- not the actual code)
int? y = 100;
long x = long.MaxValue;
y = x;
I am getting compile time error.
"Cannot implicitly convert type 'long' to 'int?'. An explicit conversion exists (are you missing a cast?).
I do have the fix ( see below the solution section), My curiosity in posting the question is of the 3 solutions which one is recommended?
Solution
y = Convert.ToInt32(x);
y = (int)x;
y = unchecked((int) x);
Thanks in advance for your suggestions
The reason you require an explicit conversion is that not all values of long
can be represented as an int
. The compiler is more or less saying 'you can do this, but you have to tell me you know what you're doing'.
Per the docs, Convert.ToInt32
will check for and throw an OverflowException
if the long
cannot be represented as an int
. You can see the implementation in the reference source - it's just this check and then a cast.
The second two options are (usually) the same and allow the cast despite an overflow as unchecked
is the compiler default. If you change the compiler default to checked using the /checked switch then you'll get an OverflowException
if not in an unchecked
block.
As to which is 'best', it depends what your requirement is.
int
is 32-bit integral while long
is 64-bit integral.
long
can store/represent all int
values but all long
values cannot be represented by int
so long
is bigger type than int
that's why int
can be implicitly converted to long
by compiler but not vice versa.
So that's the reason we need to explicitly cast/convert long
to int
which may result in information loss if that long
is not representable asint