Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between casting in C# and VB.NET

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?

like image 659
Ignacio Soler Garcia Avatar asked Dec 09 '09 14:12

Ignacio Soler Garcia


People also ask

How many types of casting are there in C?

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.

What does casting do in C?

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.

What is type casting and its types?

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.


1 Answers

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).

like image 130
Roman Boiko Avatar answered Oct 18 '22 13:10

Roman Boiko