1
votes

I want to create a extension class for the List type so users can do

ListObject.AddDistinct("value")

I want the method to work with all types of list so:

List(Of Integer)
List(Of String) 

etc etc. My extensions is

Module ListsExtensions
<Extension()>
Public Sub AddDistinct(ByRef ls As List(Of Type), ByVal obj As Type)
    If Not ls.Contains(obj) Then ls.Add(obj)
End Sub
End Module

I've it defined as Type and also tried object but neither are accessible when I have a list of strings.

If I set it to be string it then appears..But I want something that is more generic and will work with all lists. How do I need to define it?

1
This looks like it has been asked before stackoverflow.com/questions/349064/…Shaun Wilde

1 Answers

5
votes

List(Of AnyType) is called a generic class. It's how the class works with any type yet remains strongly-typed rather than using Object.

For your extension method to be generic, you need to declare the generic type like so (I'm using T instead of Type here to follow .NET naming conventions):

<Extension()>
Public Sub AddDistinct(Of T)(ByRef ls As List(Of T), ByVal obj As T)
    If Not ls.Contains(obj) Then ls.Add(obj)
End Sub