A generic type is one programming construct that adapts to do the same operations for many data types. When you write generic code, you do not have to write different implementations for each possible data type.
Example generic class
Class Container[T] Method Add(item As T) Dim temp As T End Method End Class
Permitted generic constructs
You can define and use generic classes, structures, traits, and procedures. Know that the ViviFire standard libraries provide many commonly used generic constructs that you can use in your code.
Although procedures are not types, you can define and use generic procedures. See Generic Procedures for more information.
How generic types help
You use generic types to declare some different programming elements, where each operates on specified data types. The alternatives to a generic type are:
- One type operates on the object data type.
- A set of different implementations of the type, each coded differently to operate on one data type, such as
String, or a user-defined class or structure.
Generic types are better than these alternatives because of:
- Type safety – TODO
- Performance – TODO
- Decreased code size – TODO
- Code that you can use again – TODO
- Generic algorithms – TODO
Example of a constraint
Types of constraints
There are five types of constraints.
- The type argument must be one in a particular branch of inheritance.
- The type argument must be either a reference type or a value type.
- The type argument must implement one or more traits.
- The type argument must implement a parameterless constructor.
- Two or more of the above in the shown sequence.
If you need to specify more than one requirement, you can put a comma between each one.
Alternatively, you can use
Where again and again, each on a different line.
- If a sub-type is necessary, then use one of the operators
- If a reference type is necessary, then use “
- If a value type is necessary, then use “
- If a trait is necessary, then use “
- If a constructor is necessary, then use “
Constructor()”. The parentheses are mandatory.
See Where Clause (Generics) for more information.
Examples of many constraints
Class MyClass[T] Where T Is Class Does Compare Constructor() ' ... End Class
Class MyClass[T] Where T Is Class, T Does Compare, T Constructor() ' ... End Class
Class MyClass[T] Where T Is Class Where T Does Compare Where T Constructor() ' ... End Class