From what I can find on google, VB.NET only has one-statement lambdas, and not multi-statement anonymous functions. However, all the articles I read were talking about old versions of VB.NET, I couldn't find anything more recent than vs2008 beta 1 or 2.
So the question: How can I do this in VB.NET?
C# code:
private void HandleErrors( Action codeBlock ){
try{
codeBlock();
}catch(Exception e){
//log exception, etc
}
}
HandleErrors(() => {
var x = foo();
x.DoStuff();
etc
});
In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
Anonymous functions, lambda expressions, or function literals are all the same thing. Lambda (or \lambda) is the name given to anonymous functions in some languages like Python. These are functions not bound by an explicit identifier.
Anonymous MethodAnonymous methods in C# can be defined using the delegate keyword and can be assigned to a variable of delegate type.
A lambda expression is a function or subroutine without a name that can be used wherever a delegate is valid. Lambda expressions can be functions or subroutines and can be single-line or multi-line. You can pass values from the current scope to a lambda expression.
It does in VB10:
Dim food = New With {
.ID = 1,
.Name = "Carrot",
.Type = (
Function(name As String)
If String.IsNullOrEmpty(name) Then Return String.Empty
Select Case name.ToLower()
Case "apple", "tomato": Return "Fruit"
Case "potato": Return "Vegetable"
End Select
Return "Meat"
End Function
)(.Name)
}
Dim type = food.Type
Or, corresponding to your code:
Sub HandleErrors(codeBlock As Action)
Try
codeBlock()
Catch e As Exception
' log exception, etc.
End Try
End Sub
HandleErrors(Sub()
Dim x = foo()
x.DoStuff()
' etc.
End Sub)
Visual Basic .NET has only lambda expressions.
It does not support 'anonymous delegates" in the current version, though it will (and on multiple lines at that) in VS2010.
Right now the only option is to declare your method somewhere and pass it with the Addressof operator.
VB9 has only single-line anonymous functions. We're adding full statement and multi-line lambdas in VB10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With