From VB.NET to C# and Back Again, Part 3
By Darren Neimke and Scott Mitchell
In Part 2 we looked at more advanced differences between VB.NET and C#: namely the differences in operator usage; array usage, declaration, and allocation; and the functional differences. In this final part, we will (finally) look at a complete C# ASP.NET Web page and convert it to C#!
Putting the Pieces Together - Converting an Actual ASP.NET Web Page
Now that we've examined the major syntactical differences between VB.NET and C#, let's attempt to apply
what we've learned and convert a C# ASP.NET Web page to VB.NET. The following code, written in C#, reads
in the Products table from the GrocerToGo database into an OleDbDataReader, and
then uses data binding to bind the data reader to a DataGrid. The code is as follows:
|
One thing to notice that wasn't mentioned before: in the constant strConnString note that
to specify a backslash (\) in a C# string, we must use two consecutive backslashes
(\\). This is because the backslash is the C# escape character - that is, we can insert a
newline character using \n, or tab using \t. Therefore, to let C# know that
we want a plain-Jane backslash and not some escaped character, we have to use two backslashes.
Now, to convert this to VB.NET! First note that all of the code in the HTML section (between the
<html> and the </html>) will need no changes - we just need to
concern ourselves with the server-side script block (or code-behind page, if you're using that technique).
First, let's change all of the function statements to VB.NET-proper function statements. That is:
void Page_Load(Object sender, EventArgs e) |
becomes:
Sub Page_Load(sender as Object, e as EventArgs) |
Note that we created a Sub since the C# function's return value was void. We
also got rid of the curly braces, replacing the last one with End Sub. Finally, in the
subroutine's arguments, we reordered the Type and arg names such that the arg name
comes first followed by the Type. Next, we'll want to do some ticky-tack changes, such as renaming
all of the constant delimiters in C#, //, to their VB.NET equivalents, ',
removing all of the semicolons, and changing the C# string concatenation operator of + to
the VB.NET operator, &.
Next, let's change all variable (and constant) declarations from the C# format of Type VariableName
to the VB.NET format of Dim VariableName as Type; for example, we'll make the
following (among other) changes:
const string strSQL = "SELECT * FROM Products"; -- becomes -- |
Once we complete this we are, miraculously, done! The use of methods and objects from the .NET Framework
(such as the OleDbCommand class, are identical regardless of the language being used. Note
that translating from VB.NET to C# requires a bit more attention when it comes to the casing of classes
and methods, since C# is case-sensitive. The final VB.NET translation can be seen below:
|
Happy Programming!




