4.10. Indexers, Properties, and Events

For the most part, generics represent a graceful extension to the languages of the .NET platform. That said, there are some areas of classes where generics cannot be applied. Specifically, generics cannot be applied to the indexers, properties, or events that appear in your classes. Each of these members can reference type parameters in their signature. However, they are not allowed to directly accept type parameters. That distinction may not be clear. Following is a quick example that will help clarify this point. Let's start with an example that would be considered valid:

[VB code]
Imports System.Collections.Generic

Public Delegate Sub PersonEvent(Of T)(ByVal sender As Object, ByVal args As T)

Public Class Person(Of T)
    Private _children As List(Of T)

    Public Sub New()
        Me._children = new List(Of String)()
    End Sub

    Public Property Children() As List(Of T)
        Get
            Return Me._children
        End Get
        Set(ByVal value As List(Of T))
            Me._children(index) = value
        End Set
    End Property

    Default Property Item(ByVal index As Long) As T
        Get
            Return Me._children(index)
        End Get
        Set(ByVal value As T)
            Me._children(index) = value
        End Set
    End Property


    Event itemEvent As PersonEvent(Of T)
End Class
[C# code] using System.Collections.Generic; public delegate void PersonEvent<T>(object sender, T args); public class Person<T> { private List<T> _children; public Person() { this._children = new List<String>(); } public List<T> Children { get { return this._children; } set { this._children ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.