user489041
user489041

Reputation: 28294

Help with Generics in VB

Im new to VB. I am coming from a Java background. In the following code


Sub PrintList(Of T)(ByVal list As List(Of T))
        For Each obj As T In list
            Console.Write(obj.ToString() + " ")
        Next
        Console.WriteLine()
    End Sub

Can someone help me to understand what Sub PrintList(Of T)(ByVal list As List(Of T)) means? Why do you need the (Of T) part? Why isn't (ByVal list As List(Of T)) sufficient?

Upvotes: 2

Views: 81

Answers (2)

MGZero
MGZero

Reputation: 5963

Adding to what Jon Skeet said, this sub appears to be able to take any type of list. If PrintList(Of T) was just PrintList, then you would be stuck specifying what type of List you want to use for your parameter. You could no longer have 2 calls to this sub taking two different types of lists without overloading the sub.

What I mean by 2 different types of lists is:

List(of string)
List(of integer)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499760

In Java, this would be something like:

public static <T> void printList(List<T> list)

The (Of T) after PrintList is the equivalent to the <T> before void in the Java version. In other words, it's declaring the type parameter for the generic method.

Upvotes: 5

Related Questions