The following code works fine in C#.
Int32 a, b;
Int16 c;
a = 0x7FFFFFFF;
b = a & 0xFFFF;
c = (Int16)b;
But this code crash with a OverflowException in VB.NET.
Dim a, b As Int32
Dim c As Int16
a = &H7FFFFFFF
b = a And &HFFFF
c = CType(b, Int16)
Both code snippets seem the same to me. What is the difference and how can I get the C# code converted to VB.NET?
There are basically 5 different in-built type casting functions available in the C language. These are: atof(): We use it to convert the data type string into the data type float.
Type casting refers to changing an variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float.
A type cast is basically a conversion from one type to another. There are two types of type conversion: Implicit Type Conversion Also known as 'automatic type conversion'. Done by the compiler on its own, without any external trigger from the user.
From MSDN:
For the arithmetic, casting, or conversion operation to throw an OverflowException, the operation must occur in a checked context. By default, arithmetic operations and overflows in Visual Basic are checked; in C#, they are not. If the operation occurs in an unchecked context, the result is truncated by discarding any high-order bits that do not fit into the destination type.
EDIT: If you're going to port code from C# to VB.NET, you may be interested in differences between them. Also compare and explicitly set compiler settings to be the same as default settings in C# (when needed).
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