Extension Method and Type Constraints

I am starting to play with extension methods, and I ran into this problem: In the following scenario, I get:

"the extension method has a type constraint that can never be executed"

Public Interface IKeyedObject(Of TKey As IEquatable(Of TKey))
    ReadOnly Property InstanceKey() As TKey 
End Interface

<Extension()> _
Public Function ToDictionary(Of TKey As IEquatable(Of TKey), tValue As IKeyedObject(Of TKey))(ByVal l As IEnumerable(Of tValue)) As IDictionary(Of TKey, tValue)
     'code
End Function

But it works if I replace IKeyedObject (Of k) with IKeyedObject (Of Integer)

  <Extension()> _
    Public Function ToDictionary(Of TKey As IEquatable(Of TKey), tValue As IKeyedObject(Of TKey))(ByVal l As IEnumerable(Of tValue)) As IDictionary(Of TKey, tValue)
        'code
    End Function

Am I missing something? in any way can i do what i want here?

Thanks in advance

+3
source share
1 answer

The extension method '<methodname>' has type restrictions that can never be satisfied.

I read the following about this error on MSDN :

, , , , [...]

TKey, TValue l, . , .


. , , :

Dim values As IEnumerable(Of TValue) = ...

Dim dictionary As IDictionary(Of ?, TValue) = values.ToDictionary()
'                                ^                                            '
'                                where does the compiler get this type from?  '

, , , à la values.ToDictionary(Of TKey)(), , -, .

+4

Source: https://habr.com/ru/post/1764496/


All Articles