Kirk Evans Blog

.NET From a Markup Perspective

VB.NET Generics and System.Action delegate

VB.NET Generics and System.Action delegate

  • Comments 1

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.

  • But you're coding it like a squiggly character (C#) coder. Allow me to help.

    Sub iterate1(ByVal list As DemoList(Of String)) , for example, should be:

    Sub Iterate1(ByVal someParamNameOtherThanList As DemoList(Of String))

    Perhaps something final like this:

    Sub Iterate1(stringList As DemoList(Of String))

Page 1 of 1 (1 items)
Leave a Comment
  • Please add 7 and 4 and type the answer here:
  • Post
Translate This Page