10.7. Applying Constraints

Anytime you choose to apply constraints to your generic types, you're narrowing the applicability and reusability of that type. And, via constraints, you're also influencing heavily the scope of what can be achieved within the implementation of your generic types. The next set of items point out some specific topics you'll want to consider as you apply constraints to your type parameters.

10.7.1. Item 15: Select the Least Restrictive Constraints

In selecting an appropriate constraint for a type parameter, you should attempt to choose the constraint that gives you the minimum level of accessibility you need without imposing any unneeded, additional constraints on your type parameters. Here's a quick example that illustrates how a constraint might be overly restrictive:

[VB code]
Public Interface IPerson
    Sub Validate()
End Interface

Public Interface ICustomer
    Inherits IPerson
End Interface

Public Interface IEmployee
    Inherits IPerson
End Interface
Public Class TestClass(Of T As ICustomer)
    Public Sub New(ByVal val As T)
        val.Validate()
    End Sub
End Class
[C# code]
public interface IPerson {
    void Validate();
}

public interface ICustomer : IPerson { }

public interface IEmployee : IPerson { }

public class TestClass<T> where T : ICustomer {
    public TestClass(T val) {
        val.Validate();
    }
}

In this example, you have a hierarchy of interfaces where IPerson is at the base and has descendent interfaces for ICustomer and IEmployee. Now, in your TestClass, you're currently ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.