Translating C to VB .NET


Translating C# to VB .NET

Before diving straight into our C# listings, let s look at a chunk of sample code to get a feel for how the language looks.

Here, we have a standard C# snippet that does something pretty simple. It s a function called readTextFromFile that takes a filename as an argument and returns a string containing the text from that file:

 public string readTextFromFile(string filename)  {              // reads data from a text file              try              {                           string strText;                           System.IO.StreamReader objReader =                           System.IO.File.OpenText(filename);                           strText = objReader.ReadToEnd();                           objReader.Close();                           return strText;              }              catch              {                           return "";              }  } 

And here is the corresponding code in Visual Basic .NET:

 Public Function ReadTextFromFile(ByVal Filename As String) As String      ' Reads data from a text file      Try          Dim strText As String          Dim objReader As System.IO.StreamReader = _              System.IO.File.OpenText(Filename)          strText = objReader.ReadToEnd          objReader.Close()          Return strText      Catch          Return ""      End Try  End Function 

You probably feel more at home with the VB .NET version; however, you can easily spot the common elements. The comments. The declaring of a variable. The Try-Catch blocks. Arguments into the procedure. It s all there, just organized in a slightly different way.

The following 22 pointers highlight the key differences in the C# language. When you re converting a code snippet you don t understand, one of these sections should demonstrate the VB .NET equivalent. Just look up the heading that s most relevant, then use the instructions or table within the section to translate the C# code into VB .NET.

Ready? Let s go!

Translation Listing

Here s a quick reference list of the 22 points we ll be covering in this brief translation guide:

  1. Comments: // welcome to C#

  2. Remove the End-of-Line Semicolon;

  3. Data Types: int, bool, float, DateTime

  4. Functions: public bool writeEventLog(string entry)

  5. Methods : public void activateAlarm()

  6. Variables : string strText;

  7. String Contents: \n and @

  8. Objects: myObject = new myClass();

  9. Scope: public, private, internal, static

  10. Arguments: ref and out keywords

  11. Arithmetic: x++;

  12. If-Then: if (x > y) { } else { }

  13. Comparison: == and != and & and

  14. Select Case: switch {x} { }

  15. Loops : for (x=1; x<=10; x+=1) { }

  16. Errors: try { } catch { } finally { }

  17. The Mystery of this

  18. Events: obj.event += new class.delegate(handler);

  19. Classes: Properties

  20. Classes: Constructors and Finalizers

  21. Class Interfaces: myInterface myObject2 = (myInterface)myObject1;

  22. Class Inheritance Keywords: base, virtual, abstract, sealed

1. Comments: // welcome to C#

You can easily spot comments in C#. They come in three different formats ” regular comments, multiline comments, and XML comments ”but they always begin with at least one forward slash. In VB .NET, these are declared using an apostrophe character at the start of each new comment line.

Here are examples of regular and multiline comments in C#:

 // accepts an order number and returns courier  /* this is a comment that spans     multiple lines */ 

And here s how they d look in VB .NET:

 ' this is a regular comment  ' this is a comment that spans  ' multiple lines 

C# also supports XML comments. VB .NET, however, doesn t, so you ll need to convert these to regular comments.

2. Remove the End-of-Line Semicolon;

Every statement in C# ends with a semicolon, which allows code to span multiple lines without the need for a continuation character ”simply a semicolon when the end of the statement is eventually reached. In VB .NET, we remove the semicolon, plus use a continuation character (the underscore ) if our code spans multiple lines.

Here s a C# example:

 System.IO.StreamReader objReader =     System.IO.File.OpenText(filename); 

And here s how it d look in VB .NET:

 Dim objReader As System.IO.StreamReader = _     System.IO.File.OpenText(Filename) 

3. Data Types: int, bool, float, DateTime

On first glance, it would seem C# uses different data types to VB .NET. This, however, is not the case: both languages support the same data types (they have to, in order to adhere to the Common Language Runtime specification, the heart of the .NET Framework). However, they do call them different things.

For example, a bool in C# is a Boolean in VB .NET. To help you translate, here s a table demonstrating the differing data types:

C# DATA TYPE

VB .NET EQUIVALENT

int

Integer

float

Single

DateTime

Date/DateTime

bool

Boolean

null

Nothing

4. Functions: public bool writeEventLog(string entry)

Functions in C# are not explicitly referred to as functions, but are rather just procedures with return data types. They can be easily converted to VB .NET by adding a keyword or two and changing the positioning of the data types.

Here s an example function declaration in C#. You can see that the curly brackets define the boundaries of the procedure:

 public bool isUserOnline(int id)  {             // code goes here  } 

And here s the equivalent code in VB .NET. You can see I ve added the Function keyword, altered the arguments, and edited and repositioned the data types:

 Public Function IsUserOnline(ByVal id As Integer) As Boolean      ' code goes here  End Function 

5. Methods: public void activateAlarm()

C# doesn t have methods as VB .NET developers would know them. Rather, it has procedures with void return types, meaning they return nothing. To translate into VB .NET, once again you need to add a few keywords and reposition the VB .NET equivalent data types.

Here s a C# example of a skeletal subroutine. The void keyword represents its return data type:

 public void signout()  {      // code goes here  } 

And here s how you d write that in VB .NET:

 Public Sub Signout()      ' code goes here  End Sub 

6. Variables: string strText;

Declaring variables in C# is done in reverse VB .NET style. In VB .NET, we Dim (your variable name ) As (your data type) . In C#, you forget the Dim and As and simply declare your data type first followed by the variable name.

Here are a couple of examples demonstrating C# variable declarations:

 bool blnAvailable;  int intUserid = 5;  string strText, strData; 

And here s how you d write something like that in VB .NET:

 Dim blnAvailable As Boolean  Dim intUserid As Integer = 5  Dim strText, strData As String 

7. String Contents: \n and @

If you see any suspicious-looking strings in C# code, be warned : you may be looking at an escape character . These begin with a backslash and are interpreted as special characters, such as a tab or line feed. VB .NET does not support escape characters , so you ll need to replace these with the character equivalent.

The most common C# character literal is \n , which represents a new line in a string. To translate this across to VB .NET, you ll need to replace it with the vbNewLine constant, or character codes 10 and 13. You may also see double forward slashes , such as c:\\data.txt . These are interpreted as a single slash and can be written as such in VB .NET.

If you see a backslash followed by any other character, look up escape characters in the help index and use the relevant character or constant in your ported VB .NET code.

Watch out, though: if you see the @ character before the string, it s being interpreted literally . That means something like this in C#:

 x=@"This is not \n a new line"; 

is interpreted literally as \n and not a new line. Just be careful when translating across.

8. Objects: myObject = new myClass();

Declaring objects in C# is pretty similar to the way in which you handle variables, except with the occasional new keyword thrown in for good taste. Once again, translating to VB .NET is simply a case of switching the data types and their positioning.

Here are a couple of C# examples. The first creates a placeholder for an object, then sets it to a new instance of a class. The second declares and creates a new instance in one line:

 // first example  myClass myObject1;  myObject1 = new myClass();  // second example  myClass myObject2 = new myClass(); 

And here s how this C# code would port across to VB .NET. However, as MyClass is a reserved word in VB, I ve changed the name of the class to MyClassItem for demonstration purposes:

 ' First example  Dim MyObject1 As MyClassItem  MyObject1 = New MyClassItem()  ' Second example  Dim MyObject2 As New MyClassItem() 

9. Scope: public, private, internal, static

Scope in C# works in pretty much the same way as in Visual Basic. You may see public and private keywords preceding the actual declaration. There are, however, a couple of extras you might find in C# code: internal and static .

The internal keyword is the equivalent of Friend in VB .NET. It allows that particular variable or object to be used from anywhere within its assembly. Programs using the assembly cannot access it. To convert to VB .NET, simply replace internal with Friend .

The static keyword in C# has two possible equivalents in VB .NET. If it s used to declare a variable inside a chunk of code, stick with the Static keyword in VB: such static variables retain their values even after the termination of the procedure in which they are used. If, however, it s used to declare the scope for a procedure itself or a public variable, replace with the Shared keyword: this makes the procedure available without requiring a new instance of its class. In brief: replace static with Shared if it s used to declare a procedure or external variable; otherwise , keep it as is.

10. Arguments: ref and out keywords

In Visual Basic 6, the default method of passing arguments was by reference. In VB .NET, it s by value, using the ByVal keyword. C# is exactly the same, passing arguments by value as its default setting, but it doesn t use a keyword to explicitly declare this.

So, if you look at an argument and it has no extra keywords, the value is being passed by value.

If your argument utilizes the ref keyword, however, it s being passed by reference. Simply replace ref with the VB .NET equivalent keyword, ByRef .

There s a third possibility: the C# keyword out , which has no direct VB .NET equivalent. This is used for passing uninitialized variables, where the actual value is ignored and the variables only real use is for passing data back out of the procedure. This has no real relevance in VB because uninitialized variables can be passed in regardless. Therefore, replace out with the VB .NET keyword, ByRef .

11. Arithmetic: x++;

When it comes to arithmetic, C# and VB .NET are very similar. However, three specific operands are particular to C# that can confuse the developer when porting to Visual Basic.

Here s a list of the differences, alongside equivalent VB .NET code:

C# CODE

VB .NET EQUIVALENT

x++;

x+=1

x--;

x-=1

x = x % 100

x = x Mod 100

12. If-Then: if (x > y) { } else { }

In both C# and VB .NET, the If-Then flow is relatively similar. The main difference, however, is that C# uses those {curly brackets} to define the boundaries of code that runs if a particular condition is met.

Here s a sample If statement in C#. Note the lack of a Then keyword, plus the surrounding brackets around the statement to evaluate:

 if (blnOnline)  {             // do something  }  else  {             // do something else  } 

Now, the exact equivalent in VB .NET:

 If blnOnline Then     ' Do something  Else     ' Do something else  End If 

We can clearly see that, to convert this C# statement over to VB .NET, we just remove the brackets and add a couple of extra keywords. Nothing too drastic there.

13. Comparison: == and != and & and

When using logical If statements, you often compare two particular values. However, C# and VB .NET have different ways of doing this. Equal-to , Not-equal-to , And , and Or are all operands that the two languages represent in vastly different ways. Here s how:

C# CODE

VB .NET EQUIVALENT

if (x == y) { }

If x = y Then

if (x != y) { }

If x < > y Then

if (foo & bar) { }

If foo And bar Then

if (foo & & bar) { }

If foo AndAlso bar Then

if (b1b2) { }

If b1 Or b2 Then

if (b1b2) { }

If b1 OrElse b2 Then

if (!b1) { }

If Not b1 Then

~ (as bitwise operator)

Not

14. Select Case: switch {x} { }

The switch statement is C# s equivalent of a Select Case . The problem is, the statement is so messy that most C# developers tend to opt for a nested If-Then equivalent. But, just in case you encounter it, let s look at an example:

 switch (variable)  {               case "x":               case "y":                          // code 1                          goto case "z";               case "z":                          // code 2                          break;               default:                          // code 3                          break;  } 

And now here s how that code may look in VB .NET:

 Select Case variable      Case "x", "y"         ' Code 1         ' "goto case" not supported  see tip      Case "z"         ' Code 2      Case Else         ' Code 3  End Select 

From this comparison, it s not only easy to see how to transport the C# version over to VB .NET. It s also quite apparent why the keyword-extrapolated C# switch statement is little seen in the developer world.

TOP TIP  

Watch out! There is a very small difference between the C# and VB .NET code here. The goto case statement in C# doesn t have a VB .NET equivalent. It s used to tell C# to skip to another case and evaluate it, whereas VB .NET simply exits the Select Case statement after it s found a match and run the relevant code. It s probable that this won t affect you in the slightest, but, if your code needs to continue evaluating every case statement, convert it into one big If-Then-ElseIf statement in VB .NET.

15. Loops: for (x=1; x<=10; x+=1) { }

Loops in C# look very different to loops in VB .NET. In fact, you can look at a C# loop and suddenly thank goodness you re on the Visual Basic side of the fence. A C# loop is almost like a manual VB loop, where you increment the loop number in code, set the increment yourself, specify the starting point, and so on.

Let s look at a C# sample. The top line in particular needs explanation. The arguments after the for statement are (initializer; looping condition; iterator) . Here, the initializer is an integer variable called x , which is initially set to 1. The condition is that it should loop while x is less than or equal to 10. The iterator states that x should increase by 1 with each loop round:

 for (int x=1; x <= 10; x++)  {           // code goes here           break;    // exits the loop           // code goes here           continue; // skips to end of loop           // code goes here  } 

Now let s look at the exact same loop, but this time implemented in VB .NET:

 Dim x As Integer  For x = 1 To 10      ' code goes here      Exit For ' exits the loop      ' code goes here      GoTo EndOfLoop ' skips to end of loop      ' code goes here  EndOfLoop:  Next 

If the iterator in the C# example would have increased the x counter by more than one, we would ve needed to add the Step keyword to the end of our VB .NET For loop.

There are more than just For loops in the programming world, however. You also have While , Do , and For Each loops. Let s look at a quick conversion table for these slightly-less-complex loop types:

C# CODE

VB .NET EQUIVALENT

while ( condition ) {

While condition

}

End While

do {

Do

} while ( condition );

Loop While/Until condition

foreach (datatype varname in collection) {

For Each varname In collection

}

Next

16. Errors: try { } catch { } finally { }

The Try Catch Finally method of handling errors in VB .NET applies equally in C#. However, as ever, there s a slight syntax difference: C# defines the error handling blocks through curly brackets, rather than the VB .NET method of writing code under each statement then finishing with an End Try command.

Here s a sample chunk of C# Try Catch Finally error handling code:

 try  {             // code  }  catch (System.Exception e)  {             // code             string strErrorMsg = e.Message;  }  finally  {             // code  } 

Now, here s how that code would look in VB .NET. As you can see, it s practically the same:

 Try      ' code  Catch e As System.Exception      ' code      Dim strErrorMsg As String = e.Message  Finally      ' code  End Try 

So, when dealing with Try Catch Finally blocks, simply remove the curly brackets and add an End Try . Sorted!

17. The Mystery of this

You ll see the this keyword used frequently in C# code. It s often misinterpreted, but is quite simply the equivalent of the VB .NET Me keyword. It refers to the base object: if you re behind a form, it refers to your form; if you re writing code for a class, it refers to the class. Simply replace this with Me .

18. Events: obj.event += new class.delegate(handler);

Surprise, surprise: events in C# are handled differently than in VB .NET. In C# you create an event by setting up a delegate (an event signature object), then declare an item of that delegate type. VB .NET can use delegate objects, too, as the following conversion table shows, but developers typically opt for the more common (and simpler) method of using the Event keyword.

I won t be explaining the intricacies of delegates here ”look up delegates, events and in the help index if you want to learn more ”but I ve created the following table containing common C# event code, the VB .NET equivalent, and a description as to what each line is doing.

So, take that chunk of C# code, rearrange each line a little, slot in the appropriate keywords, and you re rolling. 348

DESCRIPTION:

Set up a delegate

C# CODE:

public delegate void myDelegate();

VB .NET EQUIVALENT:

Public Delegate Sub MyDelegate()

DESCRIPTION:

Declare event based on delegate

C# CODE:

public myDelegate myEvent;

VB .NET EQUIVALENT:

Public Event MyEvent() As MyDelegate

DESCRIPTION:

Call an event

C# CODE:

myEvent();

VB .NET EQUIVALENT:

RaiseEvent MyEvent()

DESCRIPTION:

Add procedure to run when event fires

C# CODE:

myObject.myEvent += new myEventClass.myDelegate (myProcedureToRunForThisEvent );

VB .NET EQUIVALENT:

AddHandler MyObject.MyEvent, AddressOf myProcedureToRunForThisEvent

19. Classes: Properties

Properties in C# look slightly different to VB .NET. They use the {block format} you re probably getting used to by now, plus the Set portion doesn t explicitly pass in a value argument. Converting to VB .NET simply involves a little editing.

Here s a sample C# property:

 private string strName;  public string customerName  {           get     {                   return strName;     }           set     {                   strName=value;           }  } 

And now, the equivalent in VB .NET. As you can see, the conversion is easy:

 Private strName As String  Public Property CustomerName() As String     Get         Return strName     End Get     Set(ByVal Value As String)         strName = Value     End Set  End Property 

20. Classes: Constructors and Finalizers

The code used for declaring namespaces and classes in C# ports easily across to VB .NET. Simply remove the curly brackets and add the End Class statement. Leave VS .NET to sort out the casing for you ”and you re up and running!

However, you ll never see a New or Finalize procedure in your C# class ” methods we d use in VB .NET as constructors and finalizers. Why? Because, yup, they re different in C#.

Here s a sample class in C#, containing just a constructor and a finalizer. As you can see, the constructor is an almost procedure bearing the name of the class. The finalizer is similar, although with a proceeding ~ squiggle . (If you remember, ~ represents Not , meaning that this is the opposite of the constructor):

 public class sampleClass  {           public sampleClass()     {                    // constructor code           }           ~sampleClass()           {                    // finalizer code           }  } 

Here, we have the equivalent code in VB .NET. As you can see, we simply replace the C# constructor and finalizer with the VB .NET New and Finalize equivalent. We also add one simple line of code to finalize the base class ( MyBase.Finalize ), code that is automatically generated behind the C# scenes yet needs to be manually added in VB .NET:

 Public Class SampleClass      Public Sub New()         ' Constructor code      End Sub      Protected Overrides Sub Finalize()         MyBase.Finalize()         ' Finalizer code      End Sub  End Class 

21. Class Interfaces: myInterface myObject2 = (myInterface)myObject1;

If the code you are reading uses interfaces, you ll need to do some sharp editing to make it work in Visual Basic. Of course, VB .NET uses the Implements keyword to inherit an interface. C#, however, is a little less explicit, simply listing the class to inherit the interface from after the main class definition. The way in which it implements polymorphism is also a little puzzling ”no CType here, thank you very much.

Here s a table that demonstrates possible C# class interface code, alongside a description and the VB .NET equivalent. Simply replace one with the other.

DESCRIPTION:

Create an interface

C# CODE:

public interface myInterface{

public void myMethod();

}

VB .NET EQUIVALENT:

Public Interface MyInterface

Public Sub Method

End Interface

DESCRIPTION:

Implement an interface

C# CODE:

public class sampleClass :

myInterface

VB .NET EQUIVALENT:

Public Class SampleClass

Implements MyInterface

DESCRIPTION:

Implementing multiple interfaces

C# CODE:

public class sampleClass :

myInterface1, myInterface2

VB .NET EQUIVALENT:

Public Class Sample Class

Implements MyInterface1

Implements MyInterface1

DESCRIPTION:

Sample implementation

C# CODE:

void myInterface1.myMethod()

void myInterface2.myMethod()

VB .NET EQUIVALENT:

Sub ProcedureName1() Implements MyInterface1.MyMethod

Sub ProcedureName2() Implements MyInterface2.MyMethod

DESCRIPTION:

Converting to an interface type

C# CODE:

myInterface myObject2 = (myInterface)myObject1;

VB .NET EQUIVALENT:

MyObject2 = CType(MyObject1, MyInterface)

DESCRIPTION:

Calling an implemented method

C# CODE:

((myInterface)myObject2).myMethod();

VB .NET EQUIVALENT:

MyObject2.MyMethod()

22. Class Inheritance Keywords: base, virtual, abstract, sealed

It s one of those controversial developer topics: inheritance, the ability for your class to inherit the interface and functionality of another. This allows you to build a common base class that other classes can build upon (that is, a Person class may be the base for both Employee and Client classes). There are frills you can take advantage of, as well: for example, you can override one of the members of the base class if you need some special functionality.

Inheritance is new to this release of Visual Basic and is the final key to turning VB into a fully object-oriented programming (OOP) language. However, whole books are dedicated to the topic of inheritance, its technical background, and why you should (and shouldn t) use it. But this isn t one of them. If you need more information, get hunting at one of the popular online bookstores or look up inheritance, overview in the help index for a quick review.

However, if you re just looking to convert your C# code over to Visual Basic, you re in luck. It s simply a matter of switching a couple of keywords. Here s the list; just replace one with the other and, hey presto!

C# CODE

VB .NET EQUIVALENT

base

MyBase

virtual

Overridable

override

Overrides

abstract

MustInherit

sealed

NotInheritable

public class childClass:

Public Class ChildClass

baseClass

Inherits BaseClass

public childClass():

Public Sub New()

base()

MyBase.New()




The Ultimate VB .NET and ASP.NET Code Book
The Ultimate VB .NET and ASP.NET Code Book
ISBN: 1590591062
EAN: 2147483647
Year: 2003
Pages: 76
Authors: Karl Moore

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net