Question What is this: Sub(x)?

groadsvb

Well-known member
Joined
Nov 13, 2006
Messages
75
Programming Experience
Beginner
I am very new to .net programming and have been asked to modifiy a program that has this statement in it.

list.ForEach(Sub(x) _processingQueue.Enqueue(x))

I dont know what the Sub(x) is so looking up information on the internet is not giving me any information. Any help understanding this is greatly appreciated.
 
ForEach method parameter is a Action(Of T) delegate, here an anonymous Sub method is supplied as argument. 'x' is the element parameter and its type is inferred from the list.
Lambda Expressions (Visual Basic)
 
To make it clearer what is happening, here is how you might do the same thing with a conventional method instead of a lambda. You could call ForEach like this:
VB.NET:
list.ForEach(New Action(Of SomeType)(AddressOf AddToQueue))
So that is explicitly creating an Action delegate that refers to the AddToQueue method. SomeType would have to be the same as the generic type of your List. AddToQueue could be implemented like this:
VB.NET:
Private [COLOR="red"]Sub[/COLOR] AddToQueue[COLOR="red"]([/COLOR]ByVal [COLOR="red"]x[/COLOR] As SomeType[COLOR="red"])[/COLOR]
    [COLOR="red"]_processingQueue.Enqueue(x)[/COLOR]
End Sub
I've highlighted the important parts that have been retained by the lambda. Everything else is implied by the usage.
 
Back
Top