Home
VB.NET
Array.ForEach Example
This page was last reviewed on Nov 10, 2023.
Dot Net Perls
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.
Array
Example. 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.
Step 1 To begin we create our array of Bird instances. We create 3 birds (all the same) just for the example.
Step 2 Here we invoke Array.ForEach and pass a lambda specified with the Sub keyword. The lambda calls Add() on each bird.
Lambda
Step 3 In the 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 Module
BIRD.ADD BIRD.ADD BIRD.ADD
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 10, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.