Search code examples
.netvb.netgenericsgeneric-programming

How to make this simple function generic in VB.NET?


Aim to Achieve :

I want the Function to accept List(Of String), Array & String and similarly return List(Of String), Array & String respectively. The Function simply adds a string (month) to the input collection. I just want to use it for string, array and list with needing to think of conversions.

I have a simple function :

Private Function addMonth(ByVal stringList As List(Of String), ByVal month As String) As List(Of String)
    Dim names As New List(Of String)
    For Each name In stringList
        names.Add(name + " (" + month + ")")
    Next name
    Return names
End Function

How can I use generic type 'T' to achieve my aim ?

It would really save me a lot of tension.. !

I am new to VB.Net.. and don't know much about generic functions !


Solution

  • You don't even need to write a new function for this. Just use .Select():

    myStringList.Select(Function(s) s & " (" & month & ")")
    

    But since you also want to accept a string input, you can overload the function like this:

    Private Function AddMonth(ByVal list As IEnumerable(Of String), ByVal month As String) As IEnumerable(Of String)
        return list.Select(Function(s) s & " (" & month & ")")
    End Function
    
    Private Function AddMonth(ByVal list As String, ByVal month As String) As IEnumerable(Of String)
       Return New String() {list & " (" & month & ")"}
    End Function
    

    Note that all of these return IEnumerable(Of String), and this is just as it should be. It's easy to convert this to a string array or string list later, but most of the time you don't want to. It's much better for performance to keep treating an object as an IEnumerable for as long as possible.