7.4. Using Multiple Constraints

Though the examples used so far have all applied a single constraint to each type parameter, you actually have the option (within some boundaries) of applying multiple constraints to a type parameter. Suppose, for example, you wanted to apply the IVisitor constraint to one of your type parameters and, at the same time, you also wanted to provide your class with access to the default constructor for that same type parameter. The syntax for expressing these two constraints together appears as follows:

[VB code]
Public Class MyClass(Of T As {IVisitor, New})
    ...
End Class
[C# code]
public class MyClass<T> where T : IVisitor, new() {
    ...
}

This is one area where VB and C# have taken fairly different approaches to their syntax. Personally, VB's use of curly brackets seems to feel more like a syntactic afterthought. Still, it gets the job done.

The only issue you're likely to run into here is determining what combinations of constraint types are valid. For interfaces, you're actually allowed to apply any number of interfaces to your type parameters. The compiler will simply verify that every attempt to access a member in your generic type can be resolved via at least one of the interfaces provided in your list of constraints. The following provides a simple example where multiple interface constraints are applied to a single type parameter:

[VB code]
Public Class MyClass(Of T As {IVisitor, IComparable(Of T), IInspector})
    ...
End Class
[C# code] public ...

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.