Home > Software design >  How to extend the List class Of any type
How to extend the List class Of any type

Time:10-22

I am trying to learn class extensions and am running into difficulty when defining the type of variables accepted in my new methods & functions. I have this simple method that I want to add to the List object that would be a short-hand for removing the final element off the list.

Imports System.Runtime.CompilerServices
Module ListExtensions
    <Extension()>
    Sub RemoveLast(FromList As List(Of ))
        FromList.RemoveAt(FromList.Count - 1)
    End Sub
End Module

I don't know what to write inside the brackets for List(Of ). For numeric operations, I have heard that I am supposed to create duplicate versions of the method with each accepted numeric type. But I want to accept lists of any type, and don't want to create a hundred of this method.

What do I write?

CodePudding user response:

(Promoting GSerg's comment to an answer...)

You can write generic methods as extension methods; in fact, Linq is all generic extension methods. The result would be something like this:

<Extension>
Public Sub RemoveLast(Of T)(ByVal this As List(Of T))
    this.RemoveAt(this.Count - 1)
End Sub

The generic argument will be inferred in the call, you don't need to specify it, e.g. this will work:

Dim myList As New List(Of Integer) From {1, 2, 3, 4}
myList.RemoveLast()

CodePudding user response:

Try this:

Imports System.Runtime.CompilerServices
Module ListExtensions
<Extension()>
Sub RemoveLast(FromList As List(Of T))
    FromList.RemoveAt(FromList.Count - 1)
End Sub
End Module
  • Related