dinsdag 4 oktober 2011

A code brainteaser: the solution

Yesterday I posted a small brainteaser, now I'll reveal what's wrong with the VB.NET code.

As you could see the code wouldn't execute because the boolean did not get set.  This is strange because when you debug the code it clearly jumps into the statement when the Action is invoked:




Now what is the subtle difference between the VB.NET code and the C# code is that C# uses the lambda syntax and VB.NET requires you to use the Sub or Function syntax. The VB.NET syntax requires you to specify whether you want the statement to provide a return value (Function) or whether it should just be a subroutine (Sub).  In this case I made a “mistake” by saying that it should be Function instead of a subroutine and since the assignment operator and the equality operator are the same symbol you hardly notice the difference.

So the fix would be the following:

Module Module1

    Sub Main()
        Dim thisShouldBeSet = False

        DoSomething(Sub() thisShouldBeSet = True)

        If Not thisShouldBeSet Then
            Throw New Exception()
        End If

        Console.WriteLine("yaay")
    End Sub

    Sub DoSomething(action As Action)
        action.Invoke()
    End Sub
End Module

So this is where the difference is in the Action class between VB.NET and C#.  From the definition of msdn:

In C#, the method must return void. In Visual Basic, it must be defined by the SubEnd Sub construct. It can also be a method that returns a value that is ignored.

In my opinion this is a flawed implementation and just allows developers to make more mistakes.  I can also see no valid reason why anyone would use a method with a return value in an Action.  If you do this because the method already exists then split it up because you’re doing too much.

Enough VB-ranting for today, till next time.

Geen opmerkingen:

Een reactie posten