Thursday, August 30, 2012

VB.NET cheat sheet

I've been doing quite a bit of programming in VB.NET recently. It's almost exactly the same as C# but a few things have caught me out. I've written up a small cheat sheet with the noticeable differences (plenty of websites will give you a huge list of irrelevant differences).

Keywords

C#VB.NET
thisMe
baseMyBase
abstractMustOverride/MustInherit
virtualOverridable
sealedNotInheritable
class Class : InterfaceImplements (statement)
internalFriend
staticShared
typeof()GetType()

If you want a static class in VB.NET, you'll need to use the Module keyword.

(One thing to note here is how much more intelligible some of the VB.NET keywords are.)

Logic

C#VB.NET
&&AndAlso
||OrElse

There is no equivalent for And and Or in C#.

Numeric type suffixes

C#VB.NET
12.34M (for Money)12.34D (for Decimal)
12.34D (for Double)12.34R (for Real)

Lambdas

C#apples.Single(x => x.Colour = "red")
VB.NETapples.Single(Function(x) x.Colour = "red")

Initialising lists and objects

C#var apple = new Fruit { Colour = "green" };
VB.NETDim apple = New Fruit With {.Colour = "green"}

C#var apples = new List { new Fruit { Colour = "red" }, new Fruit { Colour = "green" } };
VB.NETDim apples = New List(Of Fruit) From {New Fruit With {.Colour = "red"}, New Fruit With {.Colour = "green"}}

Anonymous types

C#apples.Select(x => new { Colour = x.Colour });
VB.NETapples.Select(Function(x) New With {.Colour = x.Colour})

Nulls and Nothing

If you're coming from C#, the Nothing keyword does not do what you'd expect. What would you expect the following code to do?

Dim value = ""
If value = Nothing OrElse value Is Nothing Then
    Throw New Exception()
End If

If you said "not throw an exception" you'd be wrong. Weirdly, the first condition is true but the second condition is false, so it throws. Compare with similar C# code:

var value = "";
if (value == null)
    throw new Exception();



In this case, the exception doesn't get thrown.

No comments:

Post a Comment