Applying Extension method to generic class with generic type
Asked Answered
T

1

9

I was working with the generic class in vb.net.
And it seems extension method cannot be applied to generic class without specifying the type.

I have this generic class

Public Class MyGeneric(Of T)
    'Methods and properties go here 
    '
    '
End Class  

This is Ok

<Extension()> _
Public Sub DoSomething(ByVal myGenericDoubleObj As MyGen(Of Double))

End Sub  

This is NOT Ok(IDE gives me error T as not defined.)

<Extension()> _
Public Sub DoSomethingGeneric(ByVal myGenericObj As MyGen(Of T))

End Sub

Is this something to do with the static checking of the .Net.
Saying me "Something which may you try with doing with Type T is may not compatible and I will not allow you to do it."

P.S. All the this pain I have taken as Generic Class comes from another library, And used at many different places. I am little wary of inheriting and adding this method in my inherited generic class.

Trilingual answered 8/12, 2008 at 10:11 Comment(1)
+1 for exactly what I was looking forBacchus
G
15

If you make your extension method a generic method it should work

i.e DoSomething (Of T) () instread of just DoSomething()

<Extension()> _
Public Sub DoSomething(Of T)(ByVal myGenericObj As MyGeneric(Of T))
End Sub

Hope this helps

Greensboro answered 8/12, 2008 at 10:27 Comment(1)
C# version: public static void DoSomething<T>(this MyGeneric<T> myGenericObj)Fefeal

© 2022 - 2024 — McMap. All rights reserved.