Converting from Visual Basic .NET to C#

Here are tips to use when converting code from Visual Basic .NET to C#, if you learned the languages in that order.

This tip provides tips you can use when converting code from VB .NET to C#, if you learned the languages in that order.


Assuming you took Dan Appleman's advice and learned Visual Basic .NET before learning C#, here are the things I wish someone had told me instead of having to learn it the hard way.

  1. C# is case-sensitive. Thus although both "if" and "If" are valid in VB.NET, only "if" is valid in C#.

  2. Visual Basic .NET uses "=" for both equality and assignment whereas C# uses "==" for equality and "=" for assignment.

    More on VB .NET and C#
    Learning Guide: Choosing Visual Basic .NET or C#
  3. C# uses the ";" to denote the end of a statement and thus does not need a line continuation character.

  4. C# uses braces, "{" and "}", to denote blocks of code.

  5. In C#, everything after "//" is a comment. Multiple lines can be commented out with "/* ..... */".

  6. C# distinguishes between a char (a single byte) and a string. The literals for each are shown here:

      char cFred = 'F';   // character assignment
      string strFred = "Fred";  // string assignment
    

  7. Brackets around conditions are mandatory in C#, thus the VB.NET fragment of code:

     If intFred = 1 Then
       strFred = "Fred is 1"
     End If
     
    becomes in C#
     if (intFred == 1) 
     {
       strFred = "Fred is 1";
     }
    

  8. The logical "And" and "Or" in Visual Basic .NET become just "&" and "|", thus:

    If (intFred = 1) Or (intFred = 2) Then
       strFred = "Fred is 1 or 2";
     End If
     

    becomes in C#:

     if ((intFred == 1) | (intFred == 2)) // notice the second layer of (..)
     {
       strFred = "Fred is 1 or 2";        
     }
    

  9. Whereas in Visual Basic .NET, strings can be concatenated by "+" or "&", in C#, concatenation is "+" only.
The only C# book I have needed is C# in a Nutshell from O'Reilly (ISBN 0-596-00526-1).


Do you have comments on this tip? Let us know.


This was first published in May 2004
This Content Component encountered an error

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchCloudComputing

SearchSoftwareQuality

SearchSOA

TheServerSide

SearchCloudApplications

Close