6.7. Applying Constraints

Like every other generic type, delegates also support the ability to apply constraints to their type parameters. This allows the methods that implement your delegate to invoke type-specific operations on the supplied type arguments. The syntax for declaring a delegate with constraints is fairly straightforward. The following code provides an example of a delegate with constraints applied:

[VB code]
Public Delegate Sub TestDelegate(Of T As Employee)(ByVal val As T)
[C# code]
public delegate void TestDelegate<T>(T val) where T : Employee;

With this constraint added to your declaration, you'll find that the compiler will now only allow you to create instances of this delegate using an Employee type (or one of its descendant types).

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.