The last year I’ve been involved in a mixed project containing C# and VB.Net code. Switching between them was difficult at first for me as a C# developer. In this blog post I’ll explain some of the differences in syntax between C# and VB.Net.
Abstract uses a little bit different keywords in vb as can be seen below:
Virtual syntax is also a little bit different
Generics in VB are almost the same as in C# they only have a different syntax for declaring them because the of the way that VB handles them.
List<SomeType> list = new List<SomeType>();
Dim list As New List(Of SomeType)
The major difference is the round brackets in the syntax and the use of the Of keyboard that indicates that it is of a certain type.
Event handler syntax is different than in C#. There a two methods of defining events in Vb. You can use the With Events or the Add/Remove Handler methods for that. Below I’ll give some examples of both:
The VB equivalent of the += operator for events is using the Add/Remove handler methods in VB.
This method is used to add a handler to a certain event. It takes the event as parameter and the a delegate that points to the specific method. This is done by using the AddressOf command.
Just as adding a method is done by using the AddHandler removing one is done using RemoveHandler.
The Syntax for withEvents/Handles is difficult to explain. Below I’ll give an explanation of the keywords and an code sample.
WithEvents is used on a variable and indicates that the object that this variable hold can throw an event.
The handles is used on a method and it indicates that this method is called when the event it registers to is triggered.
An Example of using WithEvents can be seen below:
In the above example I’ve created a Class “Test” with one public event named “TestEvent”
The large difference between the two methods is that when you use the WithEvents/Handles methods you’ll never know exactly when you’re eventhandlers will actually be added