Generic Constraints
From The Oxygene Language Wiki
This is a Language topic
Feel free to add your notes to this topic below.
Generic parameters can be constrained to have some characteristics, they can have a constraint that the type passed has to be a value type, or that it has to be a reference type. It can be constrained:
- to have a public constructor with no parameters
- or to descend from a specific class
- or implement an interface.
When the caller tries to use something that does not fit these constraints, it will fail during compilation, or at runtime (in the case of reflection emitted code). Once a type constraint is set, the members of the class or interface in the constraint can be used on the generic type, allowing the generic class to invoke members on the generic type.
Given that all types in .NET implement System.Object, there is an implicit constraint on that type.
Constraints in Delphi Prism are written with the where keyword after the class header or method definition.
type MyClass<T> = class(System.Object) where T has constructor, T is record; method Test<Y>(Left: T; Right: Y); where Y is class, Y is IEnumerable; end;
See Also
Area: Oxygene Language
Compiler version: Oxygene 5
Language Glossary — Keywords — Types — FAQ — How To