I have the following code:
Public Shared Function GetListAsString(ByVal data As List(Of String)) As String
Dim retVal As String = "| "
For Each obj As String In data
retVal = retVal + obj.ToString() + " |"
Next
Return retVal
End Function
It converts a List to a printable String. Right now it is set up to work with just Lists. I feel as if it should be able to work with any type of Collection. I am new to Collections and generics. When I attempt to do something like
Public Shared Function GetListAsString(ByVal data As Collection(T)) As String
Dim retVal As String = "| "
For Each obj As String In data.ToString()
retVal = retVal + obj.ToString() + " |"
Next
Return retVal
End Function
I get an error. Can anyone point me in the right direction?
You did not get a very helpful error message from the compiler. You forgot to make the function generic, it cannot produce a decent diagnostic. Let’s focus on the bigger issue:
The For loop is broken, starting with data.ToString(). Just use data. And the element type of data is T, not String. Also, since you are only enumerating the collection, you can make do with the lesser interface, IEnumerable<>, making it work on many more collection types. Thus:
Note the added
(Of T)after the function name, that’s the one that solves your original error message.