views:

161

answers:

1

I must be doing something wrong here (because really, what are the chances of me tripping over another bug in the Vb.net compiler?)

I have a static generic function in .net 2.0 Vb code, I thought it was time to "upgrade" it to be an extension method, but the compiler complains with

Extension method 'AddIfUnqiue' has type constraints that can never be satisfied.

Here's a trivial example that displays the same problem. The old static version (which works fine) followed by the 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 issue.

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

Has anyone any idea why this doesn't work? It could well be my Vb constraints (I'm more comfortable with c#), but I can't see what I've done wrong.

Thanks,

+2  A: 

It's not a bug, the reason why it doesn't compile is explained here.

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, you simply need to change your code to this:

<Extension()> _
Sub AddIfUnique(Of T)(ByVal this As List(Of T), ByVal item As T)
    ...
End Sub
Meta-Knight
You are indeed a Meta-Knight in shining armour. Thanks very much :)
Binary Worrier
My pleasure =)
Meta-Knight