Kirk Evans Blog

.NET From a Markup Perspective

VB.NET Generics and System.Action delegate

A customer indicated that they were having some problems with Generics in VB.NET and using “foreach” on it.  After a couple of emails back and forth, I realized they wanted to see how to use the ForEach method on a List or Array.  One way to use iteration is to use the “For Each” syntax, as shown in the “iterate1” method below.  .NET 2.0 adds the System.Action generic delegate, which is implemented in the List and Array types with a “.ForEach” member method.  This use is shown in the “iterate2” method below.

Module Module1

Sub Main()
Dim l As DemoList(Of String) = New DemoList(Of String)



End Sub

Sub iterate1(ByVal list As DemoList(Of String))
Dim s As String
For Each s In list
End Sub

Sub iterate2(ByVal list As DemoList(Of String))
list.ForEach(New Action(Of String)(AddressOf list.DisplayUser))
End Sub

End Module

Public Class DemoList(Of T)
Inherits List(Of T)

Sub DisplayUser(ByVal val As String)
Console.Write(” [- “)
Console.WriteLine(” -] “)
End Sub

End Class

This is a very cool capability that allows you to write tighter, more compact code while more easily leveraging existing code.

Jon – this is TWICE within the past week that I am coding VB.NET.