5.3. Apply Constraints

Anywhere you're allowed to create a generic type, you are also allowed to qualify that type with constraints. For a generic method, the application of constraints to the incoming type parameters is relatively simple. Chapter 7 looks at constraints in detail, but here's a quick peek at the mechanics of how constraints are applied to the type parameters of your generic methods:

[VB code]
Public Sub Foo(Of I As IComparable)(ByVal val1 As I)
End Sub
[C# code]
public void Foo<I>(I val1) where I : IComparable {}

As you can see, the syntax here leverages the same approach that you may have seen applied to generic classes. You simply add the interface qualifier for a given type parameter and that will allow you to treat any reference to that the type parameter as conforming to the supplied interface.

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.