Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

C#:

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 resulted in an overflow.

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

like image 994
xll Avatar asked Sep 05 '12 14:09

xll


2 Answers

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

You get the same exception in C# if you e.g. wrap your code in a checked block:

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

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

Integer overflow checks are then disabled for your entire project, but that's usually not a problem.

like image 136
sloth Avatar answered Sep 27 '22 18:09

sloth


Try first chopping the most significant bytes off the number, 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)
like image 23
carlosfigueira Avatar answered Sep 27 '22 19:09

carlosfigueira