7.5. Generic Delegate and Method Constraints

Every generic construct in the .NET Framework provides a mechanism for qualifying its type parameters with constraints. And, from the previous discussion, you've gotten to see plenty of examples where constraints were included as part of a generic class declaration. However, so far, you haven't really seen how constraints are applied to the remaining generic constructs. There's a reason for this. The constraints syntax for each of the remaining constructs is very similar to what you've already seen with generic classes. To illustrate this point, take a quick look at some simple generic delegates and methods with constraints applied to their type parameters:

[VB code]
Public Class MyClass
    Public Delegate Sub MyDelegate(Of T As IValidator)(ByVal val As Int32)

    Public Sub Foo(Of T As IValidator)(ByVal val As T)
    End Sub
End Class
[C# code]
public class MyClass {
    public delegate void MyDelegate<T>(int val) where T : IValidator;

    public void Foo<T>(T val) where T : IValidator {}
}

This probably appears just as you would expect. The C# examples offer a bit more variation, but nothing that's all that different than what you saw with generic classes.

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.