VB.NET Cheat Sheet

vb.net

I have been working with VB.NET a lot recently and as I haven’t used it in many years ran into a whole heap of differences between it and C#. So to help with this I have created a cheat sheet of how to do different things between c# and VB.NET. I will keep adding stuff to this as I find them.

Comments

c#:

// line comment

/* 
block comment
*/

VB.NET:

' line comment
rem line comment

Hex Literals:

C#:

var x = 0xAB;

VB.NET:

Dim x = &HAB 

VAR:

C#:

//Variable names in C# are case sensetive
var foo = new List<int>();

VB.NET:

'Variable names in vb.net are not case sensitive
Dim foo = new List(of int);
Dim foo as new List(of int);

Event Listeners:

C#:

//Declare event
public event EventHandler<bool> MyEvent;

//Raising event
MyEvent(this, false);

//Adding handler to event
obj.MyEvent += myHandlerFunction;

VB.NET

'Declare event
Event AnEvent(ByVal EventNumber as Integer)

'Raising events
RaiseEvent AnEvent(Number)

'Declaring object with events
Dim WithEvents MyObject As New EventClass

'Declare method to handle events
Sub MyEventHandler() Handles MyObject.EventName

Lambdas:

c#:

var foo = (x) => x * 2;

VB.NET:

Dim foo = Function(x) x * 2

Multiline:
Dim foo = Function(x)
		Return x * 2
	        End Function

Extension Methods:

c#:

Public static class MyExtensionMethods
{
	Public static void MyExtensionMethod(this string target, int index) 
	{
		//Do stuff here
	}
}

VB.NET:

Module MyExtensionMethods
	
	Public sub MyExensionMethod(string target, int index)
		'Do stuff here
	End Sub
End Module

Properites:

C#:

//Auto property
Public string Foo {get; set;}

//Property
Public string Foo 
{
	Get
	{
		return "bar"
	}
	
	Set
	{
		m_foo = value
	}
}

//Read only property
Public string Foo {get;}

VB.NET:

'Auto Property
Public property foo as string

'Property
Public property foo as string
	Get
		return "foo"
	End Get
	Set(value as string)
		m_foo = value
	End Set
End Property

'Read only property
Public readonly property Foo
	Get
		return "foo"
	End Get
End Property