0
votes

I am trying to understand the usage of lambda functions in VB.NET, using the following example. But something is not correct. Specifying 'Dim t as string = ...' doesn't work either. Can this be done?

Dim tagsList As New Dictionary(Of String, String)
Dim Name as string = "abc"
Dim t = Function(aName As String) If(tagsList.ContainsKey(aName), tagsList(aName), Nothing)
Dim Tag as string = t(Name)

Error BC30209 Option Strict On requires all variable declarations to have an 'As' clause. Error BC30574 Option Strict On disallows late binding.

1
I think you have to make it a Delegate, like Dim t as Del = Function ... See docs.microsoft.com/en-us/dotnet/visual-basic/misc/bc36642 - Nikki9696
Dim IsBob As String = If(Name = "Bob", "It's Bob!", "Not Bob") - technonaut
Thank you, that does the trick. - DuxburyDutch
I know linking out isn't preferred here but this article helped me out a lot with Lambda's: https://www.codemag.com/article/1001051/Practical-Uses-of-Lambdas - technonaut

1 Answers

0
votes

Based on the errors, it appears that you have Option Infer Off.

I'd recommend to turn Option Infer On, then your code will work exactly as presented. I can't really think of a good reason to ever have inference off.

Without type inference, you must declare the type of t. As noted in the comments, you can declare t to be [Delegate], but then you'll also have a problem at the point where you try to call. In order to get it to compile, I needed to change the right hand side to Cstr(t.DynamicInvoke(name)). A better alternative, if you're going this route, is to declare the delegate type explicitly (which must be done at class/module level), e.g.

Delegate Function RetrieveTag(ByVal name As String) As String

Then you declare t as having this type, e.g.

Dim t As RetrieveTag = ...