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?
List(Of AnyType)is called a generic class. It’s how the class works with any type yet remains strongly-typed rather than usingObject.For your extension method to be generic, you need to declare the generic type like so (I’m using
Tinstead ofTypehere to follow .NET naming conventions):