Saturday, August 8, 2009

Writing Lambda expressions in VB.Net 9.0

In one of my previous posts I have mentioned about writing Lambda expressions in C# 3.0.That post dealt with only C# and it was fine at that time as I was coding in C# only.Now the things changed and my project is in VB.Net.I struggled a lot to convert the C# code into VB.Net which contains lambda expressions.Here I am just describing how to write Lambda expressions in VB.Net
Here is the normal code which displays a message box on a button click.

AddHandler btn.Click, AddressOf Me.Clicked
Private Sub Clicked(ByVal sender As System.Object, ByVal args As RoutedEventArgs)
End Sub

Equivalent Lambda expression

Dim btn As New Button With {.Content = "Click me"}
AddHandler btn.Click, Function(senderObj, args) MessageBox.Show("Clicked me")

Very simple and neat.Isn't it?

One more scenario of Anonymous delegates

Dim compareResult As Boolean = (Function(a, b) a > b).Invoke(firstNo, secNo)

Hope the above code is clear.

We can use the same in the case of async service calls too.

The only one sad thing is VB.Net doesn't support multi line lambda expressions where C# does