tags:

views:

759

answers:

1

Hey all,

I'm currently writing a helper function in VB.NET to convert an array of enum values to a CSV, but I'm encounting a few difficulties....

I'm not sure what type of arguement my function should take if I want to make it generic enough to handle any enum I pass into it.

This is what I've got so far:

Public Shared Function EnumArrayToCSV(ByVal values() As System.Enum) As String
    Dim result As Generic.List(Of String) = New Generic.List(Of String)

    For i As Integer = 0 To values.GetUpperBound(0)
        result.Add(Convert.ToInt32(values(i)))
    Next i

    Return String.Join(",", result.ToArray)
End Function

I realise that the arguement is incorrect as I am working with an array of enums. Ideally, I'd like to be working with a generic set of enum values.

Can anyone help?

+4  A: 
Public Shared Function CSVFromEnumValues(Of T)(ByVal values As IEnumerable(Of T)) As String
    Dim sb As New StringBuilder()

    Dim delimiter As String = ""
    For Each item As T In values
        sb.Append(delimiter).Append(Convert.ToInt32(item).ToString())
        delimiter = ","
    Next item

    return sb.ToString()
End Function

Some notes on this code:

  • I have come to prefer the TypeFromType() rather than TypeToType() naming convention, because it places the types near the variable that contain them rather than the reverse.
  • This code will accept an array. It will also accept a list or most any other collection you can think of. This is a good thing- it makes your code more powerful and flexible.
  • This code is not restricted to enum values, but enum values are just a type. There's nothing special about the values themsevles. This isn't really a bad thing. It still works for enum values, so you can use it just fine. That it works for other items isn't necessarily a flaw.
Joel Coehoorn
Slight syntax error in the code aboveFor loop should probably read "For each item As T in Values"
Sonny Boy
Thanks, fixed. Spending too much time writing C# lately :o
Joel Coehoorn