13.6. Complying with Constraints
Constraints (covered in Chapter 7, "Generic Constraints") allow you to further qualify the nature of type parameters. When defining any generic type, the author of that type has the option of including type constraints that will require all incoming type arguments to match those constraints.
All consumers of generic types must consider the impact of these constraints and how it may impact what can be supplied as a type argument. This may be slightly more relevant to you if you're a J# developer and all of the generic types you use are defined externally. The only other language-specific issue you might run into here would be if someone were to impose a type constraint that was somehow incompatible with J#. Other than that, the J# approach to complying with constraints follows all the same rules and patterns that are applied as part of the other .NET languages.
In this section you build a basic example that provides a look at how constraints might influence the type arguments you use within a J# environment. First, though, you'll need to declare a generic type that includes type constraints. The following C# class declares a custom collection class that imposes two separate type constraints on its incoming type arguments:
[C# code] public interface IValidator { bool IsValid(); } public interface IProperty<K> { String GetProperty(K key); void AddProperty(K key, String value); void RemoveProperty(K key); } public class DataObjectCollection<T> : Collection<T> ...
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.