views:

44

answers:

1

I am starting to play with extension methods and i came across with this problem: In the next scenario i get a:

"extension method has a type constraint that can never be satisfied"

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? is any way i can do what i want here??

Thanks in advance

+2  A: 

Extension method '<methodname>' has type constraints that can never be satisfied.

I've read the following about this error on MSDN:

Because the method is an extension method, the compiler must be able to determine the data type or types that the method extends based only on the first parameter in the method declaration [...]

In your case, the compiler would have to be able to deduce both TKey and TValue from parameter l, which is not possible. Thus the compiler warning.


Which sort-of makes sense. After all, imagine how you're going to call your extension method:

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

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

Admittedly, the compiler could deduce the other type parameter by letting you state it explicitly, à la values.ToDictionary(Of TKey)(), but apparently it doesn't allow this.

stakx
That all being said, I *could* imagine that you would sooner or later inevitably stumble upon the issue causing this compiler error, once you've implemented the interface and extension method. (I'm curious whether this claim is true; I may also be wrong.)
stakx
Public Function ToDictionary(tValue As IKeyedObject(Of Integer))(ByVal l As IEnumerable(Of tValue)) As IDictionary(Of Integer, tValue)And so on, for each type of key, then when i use: Values.Todictionary() i can do: Values.Todictionary(Of Integer), for each type defined.
Burnsys