maandag 3 oktober 2011

A code brainteaser

Why is the following working in C# but not in VB.NET?
 
class Program
{
    static void Main(string[] args)
    {
        bool thisShouldBeSet = false;

        DoSomething(() => thisShouldBeSet = true);

        if (!thisShouldBeSet)
            throw new Exception();

        Console.WriteLine("yaay");

    }

    static void DoSomething(Action action)
    {
        action.Invoke();
    }
}

Module Module1

    Sub Main()
        Dim thisShouldBeSet = False

        DoSomething(Function() 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

The answer is very subtle and incredibly simple but it can make you ponder for a while :-)

I’ll provide the answer next time.

Geen opmerkingen:

Een reactie posten