What is the equivalent of "(byte)" in VB.NET?

Which is equivalent (byte) in VB.NET:

FROM#:

 uint value = 1161; byte data = (byte)value; 

data = 137

VB.NET:

  Dim value As UInteger = 1161 Dim data1 As Byte = CType(value, Byte) Dim data2 As Byte = CByte(value) 

Exception: arithmetic operation led to overflow.

How can I achieve the same result as in C #?

+7
source share
3 answers

By default, C # does not check for integer overflows, but VB.NET does.

You get the same exception in C # if you, for example. wrap your code in a checked block:

 checked { uint value = 1161; byte data = (byte)value; } 

In the properties of the VB.NET project, enable Configuration Properties => Optimizations => Remove Integer Overflow Checks, and your VB.NET code will work just like your C # code.

Integer overflow checks are then disabled for the entire project, but this is usually not a problem.

+10
source

Try first cutting out the most significant bytes from the number, and then converting it to Byte:

 Dim value As UInteger = 1161 Dim data1 As Byte = CType(value And 255, Byte) Dim data2 As Byte = CByte(value And 255) 
+6
source

To get only the most significant byte, you can do pretty negligent

 Dim data1 = BitConvertor.GetBytes(value)(0) 

This is explicit and you will not need to disable overflow checking.

0
source

All Articles