1
votes

i'm encountering the following problem. I recently activated 'Option Strict On' and now I get an error in my LINQ query. From e As TEnum returns the following error:

Option Strict On disallows implicit conversions from 'Object' to 'TEnum'

Does anyone know how to solve this?

Public Module SelectItemPandEnumExtension
        <System.Runtime.CompilerServices.Extension()> _
        Public Function ToSelectListEnum(Of TEnum)(enumObj As TEnum) As SelectList
            Dim values = From e As TEnum In [Enum].GetValues(GetType(TEnum))
                         Select New With {.Id = e, .Name = e.ToString()}

            Return New SelectList(CType(values, Collections.IEnumerable), "Id", "Name", enumObj)
        End Function
    End Module
3
Already found solution, had to remove the 'As TEnum' - Micclo
Congrats, now you can add it as an answer to your own question and mark it as "accepted". :-) - Prutswonder

3 Answers

1
votes

I think you want this:

    Dim values As IEnumerable = From e As TEnum In CType([Enum].GetValues(GetType(TEnum)), TEnum())
                 Select New With {.Id = e, .Name = e.ToString()}

    Return New SelectList(values, "Id", "Name", enumObj)

The GetValues returns an Object(), but in addition you need to define the type of values as well. Which means you won't have to ctype it when you create the select list. (Well, assuming you also have option infer off)

1
votes

I had to remove the As TEnum.

0
votes

[Enum].GetValues returns an Object(), but you should be able to have a temporary strongly typed list:

<System.Runtime.CompilerServices.Extension()> _
Public Function ToSelectListEnum(Of TEnum)(enumObj As TEnum) As SelectList
    Dim values = From e As TEnum In New List(of TEnum)([Enum].GetValues(GetType(TEnum)))
                     Select New With {.Id = e, .Name = e.ToString()}

    Return New SelectList(CType(values, Collections.IEnumerable), "Id", "Name", enumObj)
End Function