VB.Net Compared to C#
As I mentioned earlier, VB6 is a weakly typed language. However, in VB.NET strong typing is optional. To make
VB .NET strongly typed in much the way that C# .NET is, you’d run VB .NET with the compiler option Strict
set to On. You can do this by adding the statement Option Strict On at the beginning of each code module,
or on a per project basis using the Build tab of the Property Pages for the project.
However, the VB.NET default is to run with weak typing. So, if you run the following code in VB .NET
(with Option Strict disengaged)
Dim theFloat As Double = 3.5
Dim X As Integer = 2
X = X + theFloat
MessageBox.Show(X)
the program will run without syntax errors. The value of theFloat will be rounded up and off to 4 when it
is added and assigned to the integer X.
Next, in the message box statement, the integer argument X is automatically converted to a string type, and
the value 6 is displayed.
This is convenient if it is what you want to have happen, but it is also a possible source of confusion in
more complex programs if you are not counting on the round-up. Adding 3.5 and 2 and getting 6 as the integer
result is not unreasonable (although it may not be what you expect). However, adding 2.5, 3.5, and 2 and
getting 9—which is what would happen in VB without Option Strict—is pretty weird (8 would be a better result).
The comparable code in C#,
double theFloat = 3.5;
int X = 2;
X = X + theFloat;
MessageBox.Show(X);
simply will not compile due to several conversion-related syntax errors.
You can correct the C# code easily enough by casting the double-type variable theFloat to int and using the
ToString method to display the contents of the variable X in the message box:
double theFloat = 3.5;
int X = 2;
X = X + (int) theFloat;
MessageBox.Show(X.ToString());
This code compiles and runs without any syntax errors. It also produces different results than the VB code,
truncating theFloat to 3 and displaying 5 as the result. The (int) cast has simply taken the whole-number
portion of theFloat variable. To perform the round-off operation that you’d normally expect when converting
3.5 to an integer value (e.g., 4), you need to use the explicit Convert.ToInt16 method:
double theFloat = 3.5;
int X = 2;
X = X + Convert.ToInt16(theFloat);
MessageBox.Show(X.ToString());
|