Array.ForEach
Consider an array of objects in a VB.NET program. Sometimes we may want to call a subroutine on each object. The Array.ForEach
subroutine, with a lambda, can achieve this goal.
With ForEach
, we cannot use the result of any functions we call. So we must modify the objects somehow—ForEach
does not return a result.
In this example program, we need to have an array of objects on which we can call a method. We introduce the trivial Bird class
for the example.
Array.ForEach
and pass a lambda specified with the Sub
keyword. The lambda calls Add()
on each bird.Add()
subroutine within Bird, we can do something like modify the Bird's state.Module Module1 Class Bird Public Sub Add() ' Step 3: do something to the Bird class instance in this sub. Console.WriteLine("BIRD.ADD") End Sub End Class Sub Main() ' Step 1: create an array of objects. Dim birds() As Bird = { New Bird(), New Bird(), New Bird() } ' Step 2: call Array.ForEach with a Sub to invoke on each element. Array.ForEach(birds, Sub(bird as Bird) bird.Add() End Sub) End Sub End ModuleBIRD.ADD BIRD.ADD BIRD.ADD
Sometimes calling a subroutine on each object in an array can be useful. Each object may need to have its internal fields adjusted in response to some sort of external event.