A generic type is one programming construct that adapts to do the same operations for many data types. When you write generic code, it is not necessary 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 make and use generic classes, structures, traits, and procedures. The ViviFire standard libraries supply many frequently used generic constructs that you can use in your code.
Although procedures are not types, you can make 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 one operates on the 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, for example,
String, or a user-made class or structure.
Generic types are better than these alternatives because of:
- Type safety – Generic types let the compiler do type checking. The compiler can find type errors.
- Performance – It is not necessary for generic types to box and unbox data. Each one is specially made for one data type.
- Decreased code – You write the code in a generic type only one time. If you make implementations of a type for each data type, then you must write the same code again and again. Their only differences are the data types they use. But generic types automatically make implementations for each data type.
- 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 given branch of inheritance.
- The type argument must be one of 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 must specify more than one requirement, then you can put a comma between each one.
Or 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