VB for C# programmers – a little gotcha

The debate whether to use C# or Visual Basic .NET is not uncommon for most .NET developers. Certainly, one has a distinct preference, but the general idea is that you can do in C# what you can do in VB and vice versa, because the .NET Framework is our common denominator. No, I don’t mean XML literals versus automatic properties. It’s the end result that counts.

So I’m currently involved in some VB programming when we stumbled upon something peculiar. Here’s a simplified form of what my predecessor, also preferring C#, tried to do:

Public Class PropertyClass

 

    Private m_name As String = String.Empty

 

    Public Property Name() As String

        Get

            If m_name = String.Empty Then

                Name = “Unknown”

            End If

            Return m_name

        End Get

        Set(ByVal value As String)

            m_name = value

        End Set

    End Property

End Class

Simple enough, and here’s the C# version:

    class PropertyClass

    {

        private string m_name = string.Empty;

 

        public string Name

        {

            get

            {

                if (m_name == string.Empty) Name = “Unknown”;

                return m_name;

            }

            set { m_name = value; }

        }

    }

What do you expect to happen here, using the C# version?

            PropertyClass pc = new PropertyClass();

            Console.WriteLine(pc.Name);

The output would show Unknown and that’s expected, right?

And what would it be using the VB version?

        Dim pc As New PropertyClass

        Console.Write(pc.Name)

Well, surpsingly, at least to me, the output is… nothing! Yes, you try it. If we look at the compiler output. Here’s what the C# compiler made of it:

    …
   
L_0016: brtrue.s L_0024
    L_0018: ldarg.0
    L_0019: ldstr “Unknown”
    L_001e: call instance void CSharpProperty.PropertyClass::set_Name(string)
    L_0023: nop
    L_0024: ldarg.0
    …
 

I’m no expert in reading IL, but clearly you see a call to the set_Name method. For VB, the compiler turns it into:

    L_0015: stloc.1
    L_0016: ldloc.1
    L_0017: brfalse.s L_001f
    L_0019: ldstr “Unknown”
    L_001e: stloc.0
    L_001f: nop
    L_0020: ldarg.0

It’s completely gone. The compiler simply removed the

                Name = “Unknown”

It appears there’s more difference between VB.NET and C# than I thought. I certainly hope to return to some C# code soon.