How come I can assign an ULong a literal value at creation
Dim myULong As ULong = 0
but with option strict on, I cannot increment like below?
myULong += 1
Visual Studio 2013 is telling me
Option Strict On disallows implicit conversions from 'Decimal' to 'ULong'.
I have no idea how VS makes out a decimal in that line of code...
Thanks for your input!
If two operands are of different data types, the result of an arithmetic expression will be of the data type that is more precise.
Since UInt64.MaxValue
is greater than Int32.MaxValue
adding UInt64
value to an Int32
value yields a Decimal
(see: Widening and Narrowing Conversions) not an Int32
which range is too small compared to UInt64
. The result could also be negative, so UInt64
is not a good alternative either. Actually there is no implicit conversion from UInt64
to any other integral type, not even Int64
(Long
) since it's range is smaller.
That's why you get the compiler error if you try to reassign the result to the UInt64
vaue.
You either have to cast it:
myULong = CULng(myULong + 1)
or (better) use 1UL
in the first place:
myULong += 1UL
MSDN:
Type-unsafe conversions, cause a compiler error with Option Strict On. For example, if you try to add an Integer variable to a Double variable and assign the value to an Integer variable, a compiler error results, because a Double variable cannot be implicitly converted to type Integer.
By the way, C# will automatically use the correct type, so this compiles:
UInt64 myULong = 1;
myULong += 1; // here 1 is treated as UInt64
whereas this won't compile
myULong += -1; // -1 is Int32
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