3

Practical differences between C# vs Vb.Net

 3 years ago
source link: https://www.michalbialecki.com/2021/03/22/practical-differences-between-c-vs-vb-net/?utm_campaign=practical-differences-between-c-vs-vb-net
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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 false
  • AndAlso 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:

And-test-results.png

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:

Add-test-results.png

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. 😲

enum-csharp-test.png

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!

enum-vb-test.png

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! 😊


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK