Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vb.net - Why is += operator not allowed for ULong (UInt64)?

Tags:

.net

vb.net

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!

like image 721
Florian Rubach Avatar asked Aug 30 '14 21:08

Florian Rubach


1 Answers

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 UInt64value 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 
like image 189
Tim Schmelter Avatar answered Oct 04 '22 00:10

Tim Schmelter