3

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

1
  • Your 2nd snippet doesn't compile either, fix your code. Commented Sep 13, 2010 at 14:08

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.