For around a year and a half, I’ve been working with a project that was initially written in Vb.Net, but now newer code is written in C#. It’s a great example of how one project can be written in two languages, and code in Vb.net can reference C# and the other way round.
Vb.Net and C# are very similar and are compiled to the same Intermediate Language, but I found some differences more surprising than the others.
Simple differences
Let’s start with the obvious things. Vb.Net uses simple English in its syntax, while C# uses C-based syntax. Let’s have a look at the example.
private string ReplaceAnd(string s) { if (s != null && s.Contains(":")) return s.Replace(":", "?"); return s; }
And now the same example in Vb.Net:
Private Function ReplaceAnd(s As String) As String If s IsNot Nothing And s.Contains(":") Then Return s.Replace(":", "?") End If Return s End Function
It took me some time to get used to declaring types with As
keyword. Also If
statement needs Then
, but those are the things you write once or twice and it becomes a habit.
In my opinion, the biggest changes when comparing C# with Vb.Net are:
- we don’t use brackets for code blocks
- there is no need for semicolons at the end of the instruction
- variable names are not case sensitive
- and a few more 😃
&& vs And vs AndAlso
All those simple differences are just differences in the language, but basically, code stays the same. One of my biggest mistakes when I wrote Vb.Net code was using And
as &&
operator in C#. The thing is that they are not the same.
Let’s have a look at the example. I’ll use two methods that check for null in the If statement and do a replace.
Private Function ReplaceAndAlso(s As String) As String If s IsNot Nothing AndAlso s.Contains(":") Then Return s.Replace(":", "?") End If Return s End Function Private Function ReplaceAnd(s As String) As String If s IsNot Nothing And s.Contains(":") Then Return s.Replace(":", "?") End If Return s End Function
The difference between And
and AndAlso
is that:
And
will check statement on the right side even if the statement on the left side is falseAndAlso
will not check the right side statement if the one on the left is false
To show it clearly I wrote unit tests:
<TestCase("abc:d", "abc?d")> <TestCase(Nothing, Nothing)> Public Sub AndAlsoTest(toReplace As String, expected As String) ReplaceAndAlso(toReplace).Should().Be(expected) End Sub <TestCase("abc:d", "abc?d")> <TestCase(Nothing, Nothing)> Public Sub AndTest(toReplace As String, expected As String) ReplaceAnd(toReplace).Should().Be(expected) End Sub
And the results are:
AndTest
fails, cause And
operator check both left and right side, which causes a NullReferenceException
. So if you want to check for null in the If
statement and do something else as well, just use AndAlso
.
Enforce passing a variable by value
Maybe it’s not a very significant difference, but I was surprised that it can be done.
Let’s have a look at a simple code and two tests:
<Test> Public Sub AddTest() Dim a As Integer = 5 Dim result = Add(a) a.Should().Be(6) result.Should().Be(6) End Sub <Test> Public Sub AddByValueTest() Dim a As Integer = 5 Dim result = Add((a)) a.Should().Be(5) result.Should().Be(6) End Sub Public Function Add(ByRef x As Integer) As Integer x = x + 1 Return x End Function
We have a simple Add
method, where we increment a given value by 1. We pass this variable by reference, so it should be changed as well.
Notice that in AddByValueTest
we pass (a)
and this is the way how we can pass a variable by value. Note that it only works for value types.
And the results proves that it really works like that:
Converting enum to string
This difference stunned me when I saw it and it was a final motivation to write this post. I was doing a refactoring around Vb.Net with converting enums and my colleague was doing a review of the task and said.
– Hey, cool refactoring, but I’m afraid it might not work. – said the colleague.
– Really? I run that code and it was fine. – I said.
– You might want to check that again, I even wrote a unit test, to be sure. – said the colleague.
Let’s have a look at this test. I’m converting an enum to a string.
public enum ProfileType { Person = 1, Company = 2 } [Test] public void ConvertEnumTest() { Convert.ToString(ProfileType.Company).Should().Be("2"); }
And when you run it, it fails, my colleague was right. 😲
However, I was suspicious and the code I wrote was in Vb.Net, not in C#, so I wrote another test. But this time in Vb.Net.
<Test> Public Sub ConvertEnumTest() Convert.ToString(ProfileType.Company).Should().Be("2") End Sub
And you know what? It passes!
So my original code was correct. However, Convert.ToString()
on an enum works differently in Vb.Net and C#.
Summary
Working with Vb.Net sounds like going back to the middle-ages, but in fact, I got accustomed to the Visual Basic syntax quite quick. The capabilities of both are very similar, cause it’s still the same code underneath, but I found C# slightly more concise and more intuitive as well. Maybe it’s because I preferred C++ over Pascal in school 😁
There are differences, as you saw in this article, but they do not interfere with your daily work.
I hope you like this post, have a good day! 😊
The C# equivalent of Visual Basic’s And is &.
Visual Basic also has Or and OrElse that are equivalent to C#’s | and ||.
The enum case is because, in Visual Basic there’s an implicit conversion between the enum and its underlying type and in C# there isn’t.
ProfileType.Company.ToString() yields the same result both in C# and Visual Basic.
Thanks Paulo, this is a great explanation!
Many many thanks for this.
I am an older programmer who work in Visual Basic 0.9 (Yes I go back THAT far). I never learned C or C++, and have been dreading the move in to the DotNET arena. Many thanks for giving me the confidence that my extensive knowledge of BASIC is not destined for the trash heap.. as so many of my contemporaries seem to think so.
Still. I can bore them senseless with lectures on CP/M, and the fun of pre IBM PC HA..Ha.. 🙂
I’m an ‘older programmer’ as well. I’m familiar with VB6 and VBA and C# and Javascript amongst others. VB.Net might superficially share a limited amount of common syntax with ‘classic VB’ but really they’re a world apart. And I’m sorry to be the bearer of bad news, but the old procedural way of writing VB code doesn’t translate well to VB.Net. That’s because VB.Net was built as an OO language from the ground up, it’s closer to C# than classic VB but without all the awkward combinations of squiggly brackets, angle brackets and square brackets, all book ended with the ridiculously old fashioned semi-colon statement terminator. People seem to think the C style languages are some how cool and ‘modern’, I just regard them as hangovers from the last century! I’m doing a VB.Net project now and I find coding a lot more restful than when I use C#. Every time I use VB.Net’s elegant ‘Select Case’ statement compared to the frankly ridiculously awkward C# Switch-case-break; mess I breath a sigh of relief 🙂
Other few interesting tricks about readonly properties in VB.NET 😉
VB.NET has “XML Literals” feature (not exists in c#) where developers can write xml contents and “inject” runtime values directly in the code.
Dim document As XDocument =
Readonly properties can be updated outside of constructor.
VB.NET will generate “hidden” instance private member prefixed with the underscore(“_Value”)
Public ReadOnly Property Value AS String
Sub Update()
_Value = “new value”
End Sub
Love your analysis