I love C# and I would never want to do anything to make it seem any less amazing but I have to give credit where credit is due ... to Visual Basic .NET. Yes, I said it. Both languages have been adding features inspired by the functional and dynamic programing world. However, VB .NET has went a few steps further to truly merge imperative, object oriented, dynamic and functional programing into one convenient package.
Much of this functionality comes from the fact that VB .NET has late binding built in to many of its operations. This allows the programmer to be more expressive and "get away" with more. I was aware that VB .NET had some unique features but as a C# programmer I never got around to playing around with it to see how they feel.
This changed recently when I was fooling around with lambda expressions in C#. I have been casually playing and experimenting with Haskell (a pure functional programing language) for about a year now and I have become very accustomed with just writing a lambda expression and not worrying about defining its type.
With C# 3.0 I assumed I would be able to do the same thing. I wanted to be able to write C# code that is similar to the following Haskell code:
I figured this would be done easily in C# with the lambda expressions and implicitly typed variables. So I wrote:
I was very pleased with this code, it looked very close to the Haskell. It is concise, clean and quick however it doesn't compile. You get this error:
Cannot assign lambda expression to an implicitly-typed local variable
The problem is that C# is strongly typed and is unable to determine what type f should be since it cannot determine what type x is. So, you would have to write something like this:
Now, that isn't hard to do but I don't want to have to write out that type every time I want to create a lambda expression.
I tried the same lambda expression in Visual Basic .NET and ...:
Tada!, that worked like a charm. And when I call f(2) it returns 4, and when I call f("matt") it would return "mattmatt".
This was the behavior I was looking for. This peaked my interest in VB .NET and since then I have been exploring features in it and seeing how it performs late binding to make this all happen.
After I experiment some more I will write in detail about what is really going on behind the scenes in the VB .NET Compiler.