There and Back Again

Moving between VB .NET and C#

asp:cover story

LANGUAGES: VB | C#

TECHNOLOGIES: Code Conversion

 

There and Back Again

Moving between VB .NET and C#

 

By Eric Smith

 

One interesting thing about new development tools is that everyone learning to use them is starting at the same level, no matter how much experience they may have in other areas. Everyone is learning new languages and tools at the same time. If you explore various Internet newsgroups dealing with .NET, you ll see a bit of debate about the merits of the two primary languages: Visual Basic .NET and C#. Based on the way the compilers work, the Intermediate Language code is basically the same between VB .NET and C#, but C# had a slight performance edge in early testing. The difference probably won t be enough to sway people from one language to the other, however.

 

Here s my take on the debate: You really should learn both languages. As every consultant and contractor knows, more languages equals more flexibility, which in turn leads to more projects. You may not have a choice about the language you use for a development project, so it s best to know both. This article will help you see how VB .NET and C# relate and how you can convert from one language to the other.

 

Case Sensitivity

The first rule of conversion is that C# is case sensitive, and VB .NET is not. Keywords in VB .NET are in proper case, and keywords in C# are in lowercase. Take a look at this short C# program:

 

class HelloWorld

{

   public static void Main()

   {

      int intValue = 20;

      if (intValue > 10)

          System.Console.WriteLine("Greater than 10");

   }

}

 

The converted version of this for VB .NET looks like this:

 

Class HelloWorld

   Public Shared Sub Main()

      dim intValue As Integer = 20

      If (intValue > 10) Then

         System.Console.WriteLine("Greater than 10")

      End If

   End Sub

End Class

 

I ll delve further into the syntactical differences later, but the thing you should notice is case doesn t matter in VB .NET. One line has dim in lowercase instead of proper case, and the code works fine. You can mix and match the case as you see fit, but common convention is to use proper case to make the code easier to read.

 

Unfortunately, capitalization errors are hard to find. If you were to use this snippet of code, the command-line compiler would complain with an error message:  

 

class HelloWorld

{

   public static void Main()

   {

      int intValue = 20;

      If (intValue > 10)

         System.Console.WriteLine("Greater than 10");

   }

}

 

The command-line compiler would give this enlightening message: test.cs(7,25): error CS1002: ; expected. The actual error is caused by the If keyword, which should be all lowercase.

 

If you re not used to dealing with strange messages like this one, it will catch you by surprise. If you know your semicolon is in the right place, start checking your syntax and keyword use.

 

Punctuation Conversion

A major obstacle to converting code is the use of punctuation in C#. C# syntax evolved from a mix of C++ and Java syntax, so semicolons and curly braces are used to group code into logical blocks. VB .NET, on the other hand, uses keywords to accomplish the same goal. In this snippet of C# code, note the semicolons and curly braces:

class HelloWorld

{

   public static void Main()

   {

      int intValue = 20;

      if (intValue > 10)

         System.Console.WriteLine("Greater than 10");

   }

}

 

The VB .NET code eliminates the curly braces and adds keywords to mark the end of code blocks:

 

Class HelloWorld                            

   Public Shared Sub Main()                 

      Dim intValue As Integer = 20

      If (intValue > 10) Then               

         System.Console.WriteLine("Greater than 10")

      End If

   End Sub

End Class

 

The punctuation-to-keyword changes are as follows:

  • The class starts with the Class keyword and ends with End Class instead of a closing curly brace.
  • The subroutine starts with Sub and ends with End Sub instead of a closing curly brace.
  • The If statement uses a Then instead of the curly brace. If the C# code needs more than one line in the Then section, curly braces are required.
  • The End If replaces a closing curly brace that is required when an opening one is used.

 

In general, anywhere you use an End keyword in VB .NET, you replace it with a closing curly brace in C#. For semicolons, the rules are the same as those used in C, C++, and JavaScript. Here s a short summary:

  • Each statement requires a semicolon at the end. In the previous example, each variable declaration is considered a statement. In addition, the If statement is considered to be a single statement, and, when curly braces are not used, a semicolon is placed after the Then portion of the statement.
  • Keywords immediately followed by opening curly braces (such as the Class keyword in our example above) do not require semicolons following them.

 

The C# compiler is pretty good about detecting when you are missing semicolons, but you may have to decipher an occasional error message like the one shown earlier.

 

Another change between VB .NET and C# is the lack of a continuation character in C#. For VB programmers who don t like the continuation character, this will be a welcome change. Here s a typical VB .NET statement:

 

Console.WriteLine "This is some text " _

   & "that wraps onto multiple lines."

 

The underscore marks the end of one line that continues onto the next. VB requires this character in order to wrap the line to the next. C# is more lenient with regard to arrangement, primarily because the semicolon marks the end of the statement, as shown here:

 

Console.WriteLine("This is some text "

   + "that wraps onto multiple lines.");

 

The ampersand in VB .NET changes to a plus sign in C#, but no continuation character is required to make this line break onto more than one line.

 

The last punctuation change you are likely to deal with is in a comment. In VB .NET, a comment is marked with a single quotation mark, like so:

 

i = 5      ' the rest of the line is a comment

 

In C#, you have two options for commenting text. The first is analogous to the single quote:

 

i = 5;       // the rest of the line is a comment

 

The second type of C# comment is used for multiple lines of comment text:

 

i = 5;

/*

  All this text is commented out.

*/

 

The /* marks the beginning of the comment, and */ marks the end. Be sure not to nest comments, or the compiler will complain.

 

.NET Framework Classes

One of the best features of .NET is the rich framework built by Microsoft in the form of system classes. The .NET Framework classes are arranged in a hierarchy of namespaces. For instance, the WriteLine method I used earlier is a method of the System.Console class. If you had to write System.Console.WriteLine every time you wanted to print a line of text, it would become rather annoying. For that reason, you can import or use namespaces in your application, so you don t have to write the fully qualified name. In VB .NET, you do this with the Imports keyword. In C#, you use the using keyword, as shown here:

 

Imports System 'VB

 

using System; // C#

 

The namespaces are case sensitive in C#. For example, when working with SQL Server data, you may wish to use the SQL Server client namespace. In C#, you would use the following using statement:

 

using System.Data.SqlClient;

 

A common error is to type the following line:

 

using System.Data.SQLClient; //SQL should be Sql

 

This will cause an error because the C# compiler can t find any namespace with that name. VB .NET doesn t care, but you always should use the proper name of the library to make it easier to convert to C#. The MSDN documentation always lists the exact name of the library with the correct case. By using the proper name, you make your code easier to copy or convert into C#.

 

Variables and Constants

Once you re past the punctuation and spelling hurdles, the next code to convert is your variable declarations. One major improvement in .NET is the data types being the same between languages. An integer in VB .NET used to be a 2-byte value, which caused conflicts with languages like C, in which an integer was a 4-byte value. This problem has been solved so you don t have to worry about data-type conversion any longer. The only conversion you really have to worry about is the syntax conversion.

 

The basic VB .NET declaration goes like this:

 

Dim intValue As Integer = 5

 

In C#, the same declaration looks like this:

 

int intValue = 5;

 

The assignment at the end of the line is optional. Use the following syntax to declare a constant in VB .NET:

 

Public Const MYCONSTANT As Integer = 5

 

In C#, the same constant is declared like this:

 

public const int MYCONSTANT = 5;

 

I ll describe the scope keyword public later in the article because there are some differences in these keywords between languages.

 

For object declarations, the syntax is also slightly different. The VB .NET version is:

 

Dim myobj As New MyAssembly.MyType()

 

In C#, this code would be:

 

MyAssembly.MyType myobj = new MyAssembly.MyType();

 

Operators

Converting your operators between languages is fairly easy because most of them are the same. Some of the new operators, such as += and -=, are available in both VB .NET and C#. Others, such as ++ and --, are not. The changes are shown in FIGURE 1.

 

VB .NET Operator

C# Operator

Purpose

None; Use += 1

++

Increment

None; Use -= 1

--

Increment

&

+

Concatenation

<>

!=

Not equal to

=

==

Equal to

Mod

%

Modulus division

And

&&

Boolean AND

Or

||

Boolean OR

Not

!

Boolean NOT

FIGURE 1: A comparison of VB .NET and C# operators.

 

The table in FIGURE 1 covers the most frequently used operators in both languages. C# has some additional operators that deal with bit-shifting. These don t exist in VB .NET, but functions take their place. If you re using these operators, refer to the MSDN documentation for a full list of the functions.

 

One of the problems VB programmers have when working with languages like C# and JavaScript is equality vs. assignment. In VB and VB .NET, assignment is done using a single equals sign, like this:  

 

Dim I As Integer

i = 5

 

C# also uses a single equals sign for assignment, as shown here:

 

int i;

i = 5;

 

Comparisons in VB .NET are made using a single equals sign, like so:

 

Dim i As Integer

If i = 5 Then

   ' do something

End If

 

C#, on the other hand, uses a double equals sign for comparison, like this:

 

int i = 5

if (i == 5)

(

   // do something

)

 

When you are converting code, be sure to get your operators right, or you may not like the results.

 

Control Structures

Once you have converted your variables, it s time to convert your control structures. These structures include loops and decision structures. In VB .NET, a For loop is typically written like this:

 

Dim i As Integer

For i = 1 To 10

   ' do something

   ' do something else

Next i

 

In C#, this loop is written a bit differently:

 

int i;

for(i = 1; i <= 10; i++)

{

   // do something

   // do something else

}

 

You ve already seen some if statements, but there are a few more options for the structure. The basic if in C# goes like this:

 

if (i < 5)

{

   // statement

   // statement

}

 

The condition must be surrounded by parentheses in order to be valid. VB .NET does not require these parentheses, but they won t cause an error if you use them. The equivalent VB .NET code is:

 

If i < 5 Then

   ' statement

   ' statement

End If

 

In C#, the condition has to evaluate to a True or False value, unlike in C or C++, in which a non-zero value is considered True. You can t simply say this:

 

if (i)

 

This will result in a type-conversion error unless i is a Boolean variable. In VB .NET, you can do this still unless you have Option Strict turned on, in which case you ll get the same type-conversion error. Option Strict forces you to perform all type conversions explicitly. If Option Strict is turned off (the default condition), VB .NET does most of the type conversions for you.

 

The if statement also can use an else condition, as shown here in C#:

 

if (i < 5)

{

   // statement

   // statement

}

else

{

   // statement

   // statement

}

 

For multiple If, Then, or Else statements, you can use ElseIf in VB .NET, as shown here:

 

If i = 3 Then

   ' statement

ElseIf i = 4 And blnSomeCondition Then

   ' statement

Else

    ' statement

End If

 

The C# equivalent is fairly close:

 

if (i == 3)

{

   // statement

}

else if ((i == 4) && blnSomeCondition)

{

   // statement

}

else

{

   // statement

}

 

The biggest problem in conversion is remembering the parentheses around the condition. Note that in the second if statement, a pair of parentheses surrounds the entire condition. This pair is required. The parentheses around i == 4 are optional, but recommended (for readability).

 

For comparing an expression against a list of values, you typically would use a Select Case statement in VB .NET. In C#, this statement is equivalent to the switch statement. A typical VB .NET Select Case statement looks like this:

 

Select Case intValue

   Case 1

      ' do something

   Case 2

      ' do something

   Case Else

      ' do something else

End Select

 

This code translates to the following in C#:

 

switch (intValue)

{

   case 1:

      // do something

      // do something

      break;

   case 2:

      // do something

      break;

   default:

      // do something else

      break;

}

 

The break statements mark the end of a particular value s block of code and are required, unlike other languages where you can fall through from one case to another. The designers of the C# language decided falling through caused more problems than it solved and chose to leave this feature out. The result is if you are converting from a language that supports fall-through, you ll need to use an if statement instead.

 

One thing you should note is that curly braces are not used to mark the beginning and end of each case s statements. The exception to this would be if you re using an if statement that requires curly braces. In that case, you would follow the normal syntax for the if statement inside the case section you are using. Because the structure can get confusing, you may want to consider a user-defined function here instead of putting all the code in a switch statement.

 

The other type of loop you ll need to convert is the conditional loop. Like VB .NET, C# supports conditional loops in which you check the condition at the top and bottom of the loop. Here s a top-checking loop in VB .NET:

 

Do While i < 5

   ' statements

Loop

 

The C# equivalent looks like this:

 

while (i < 5)

{

   // statements

}

 

Like the if statement in C#, the condition must be surrounded by parentheses in all C# conditional loops. This particular loop is not guaranteed to run at all because the condition could be False before we get started.

 

Checking the condition at the bottom of the loop looks like this in VB .NET:

 

Do

   ' statements

Loop While i < 5

 

In C#, this code converts to:

 

do {

   // statements

} while (i < 5)

 

Subroutines and Functions

The last major conversion task is typically to deal with the subroutines and functions you may have. In VB .NET, a subroutine is a block of code that does not return a value, and a function returns a value. C# does not have this distinction. Instead, a function can return the void data type, which means there is no return value.

 

Here is a typical VB .NET subroutine:

 

Private Sub DoSomething(strInput As String)

   ' do something

End Sub

 

This is the C# equivalent:

 

private void DoSomething(String strInput)

{

   // do something

}

 

Commas are used in both VB .NET and C# to separate multiple parameters. For a function that returns a value, VB .NET programmers have two options: set the name of the function equal to the value to be returned, or use the new Return statement. Here is a VB .NET function:

 

Private Function ReturnResult(intInput As Integer) As Integer

    ' perform calculation

   ReturnResult = intResultVariable

   ' or simply Return intResultVariable

End Function

 

The C# equivalent always uses the return statement to send back a value:

 

private int ReturnResult(intInput As Integer)

{

   // perform calculation

   return(intResultVariable);

}

 

Wrapping Up

There s not enough space to detail all the differences between syntax in VB .NET and C#, but this article should give you a good start. In my opinion, Microsoft has created two languages that are nearly equal in performance and in features to use for developing in all application environments. You no longer have to remember the variations that exist between Web and Windows applications. It will be interesting to see which language most developers choose. I m learning both.

 

Eric Smith is a Microsoft Certified Solution Developer, Microsoft Certified Systems Engineer, and Microsoft Certified Trainer. He works as a trainer and consultant in the Indianapolis area. You can visit his Web site at http://www.asptechniques.com, which covers both ASP classic and ASP.NET development. Readers may reach him at mailto:[email protected].

 

Tell us what you think! Please send any comments about this article to [email protected]. Please include the article title and author.

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish