greg greg - 4 months ago 13
Vb.net Question

Getting Error 'type parameters cannot be used as qualifiers'

I am getting this error with the following code. I must be missing something. This is pretty basic stuff.

Public Function GetSingleValue() As T
If Items.Count = 0 Then Throw New Exception(T.CommonName & " can not be found")
If Items.Count > 1 Then Throw New Exception("There are mulitple " & T.CommonName & " items found")
Return Items(0)
End Function


Items() returns a List(of T).
CommonName is a member of the class that T represents

Why am I getting this error? Alternately, is there a construct in vb.Net that would allow me to do this.

Answer

You could also apply the System.ComponentModel.DisplayNameAttribute to your classes in order to assign them a common name.

<DisplayName("Super Class")> _
Public Class MyClass
End Class

Place this function in a module

Public Function GetDisplayName(type As Type) As String
    Dim attributes = type.GetCustomAttributes(GetType(DisplayNameAttribute), False)

    If attributes.Length = 0 Then
        Return type.Name 'No DisplayNameAttribute, so use class name instead
    End If
    Return DirectCast(attributes(0), DisplayNameAttribute).DisplayName
End Function

And use it like this

Public Function GetSingleValue() As T
    Dim commonName As String = GetDisplayName(GetType(T))
    If items.Count = 0 Then Throw New Exception($"{commonName} not found")
    If items.Count > 1 Then Throw New Exception($"Multiple {commonName} items found")
    Return items(0)
End Function