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()>
    Public Function NumDistinct(Of T)(the_list As List(Of T)) As Integer
        Return the_list.Distinct().Count()
    End Function
End Module
 

The generic List(Of T) class provides a Distinct method that returns a new list containing the distinct objects in the original list. The NumDistinct function calls that method and returns the new list’s Count value.

The following code shows how a program could call this function. It creates a new List(Of String) and gives it some data. It then calls the list’s NumDistinct function.

Dim name_list As New List(Of String)
name_list.Add("Llamaar Aarchibald")
name_list.Add("Dudley Eversol")
...
 
MessageBox.Show("The list contains " &
    name_list.Count() & " entries and " &
    name_list.NumDistinct() &    " distinct entries")
 

For more information on extension methods, see the section “Extension Methods” in Chapter 16, “Subroutines and Functions.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.18.65