GENERICS AND EXTENSION METHODS
Just as extension methods allow you to add new features to existing classes, they also allow you to add new features to generic classes. For example, suppose you have an application that uses a List(Of Person). This List class is a generic collection class defined in the System.Collections.Generic namespace.
The generic class is not defined in your code so you cannot modify it, but you can add extension methods to it. The following code adds an AddPerson method to List(Of Person) that takes as parameters a first and last name, uses those values to make a Person object, and adds it to the list:
Module PersonListExtensions
<Extension()>
Public Sub AddPerson(person_list As List(Of Person),
first_name As String, last_name As String)
Dim per As New Person() With _
{.FirstName = first_name, .LastName = last_name}
person_list.Add(per)
End Sub
End Module
This example adds an extension method to a specific instance of a generic class. In this example, the code adds the method to List(Of Person). With a little more work, you can add a generic extension method to a generic class itself instead of adding it to an instance of the class.
Example program GenericNumDistinct uses the following code to add a NumDistinct function to the generic List(Of T) class for any type T. The declaration identifies its generic type T. The first parameter has type List(Of T) so this method extends List(Of T). The function has an Integer return type.
Module ListExtensions <Extension()> ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access