O'Reilly logo

Professional .NET 2.0 Generics by Tod Golding

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required