Odd behavior with common constraints in an extension method

I must be doing something wrong here (because really, what are the chances that I stumbled upon another error in the Vb.net compiler ?)

I have a static generic function in .net 2.0 Vb code, I thought it was time to "update" it as an extension method, but the compiler is complaining about

The extension method 'AddIfUnqiue' is of type that can never be satisfied.

Here's a trivial example that shows the same problem. Old static version (works great) followed by an extension method

Public Class MyStaticClass
    Public Shared Sub AddIfUnqiue(Of T, L As {List(Of T)})(ByVal this As L, ByVal item As T)
        If this.IndexOf(item) < 0 Then
            this.Add(item)
        End If
    End Sub
End Class

Module UtilityExtensions
    <Extension()> _
    Sub AddIfUnqiue(Of T, L As {List(Of T)})(ByVal this As L, ByVal item As T)
    'ERROR: Extension method 'AddIfUnqiue' has type constraints that can never be satisfied'
        If this.IndexOf(item) < 0 Then
            this.Add(item)
        End If
    End Sub 
End Module

      

The equivalent code in C # has no problem, it's just a Vb problem.

public static void AddIfUnique<T, L>(this L myList, T item) where L : List<T>
{
    if (myList.IndexOf(item) < 0)
        myList.Add(item);
}

      

Does anyone know why this is not working? It might be my Vb constraints (I'm more comfortable with C #), but I can't see what I did wrong.

Thank,

+2


source to share


2 answers


This is not a bug, the reason why it won't compile is explained here .

Because this method is an extension of a method, the compiler must be able to determine the type or data types that the method only extends to the first parameter in the method's declaration.



In your case, you just need to change your code to this:

<Extension()> _
Sub AddIfUnique(Of T)(ByVal this As List(Of T), ByVal item As T)
    ...
End Sub

      

+3


source


I would say that this is a mistake.

Funny thing, the same header works great not only in C # (as you said), but also in VB - if you remove the <Extension> attribute.



So much about "extension methods are just syntactic sugar".

0


source







All Articles