All three languages support creating and using generics. Generics are discussed in Chapter 9.
For using generics C# borrowed the syntax from C++ templates to define the generic type with angle brackets. C++/CLI uses the same syntax. In Visual Basic, the generic type is defined with the Of keyword in braces.
// C# List<int> intList = new List<int>(); intList.Add(1); intList.Add(2); intList.Add(3); // C++/CLI List<int>^ intList = gcnew List<int>(); intList->Add(1); intList->Add(2); intList->Add(3); ' Visual Basic Dim intList As List(Of Integer) = New List(Of Integer)() intList.Add(1) intList.Add(2) intList.Add(3)
Because you use angle brackets with the class declaration, the compiler knows to create a generic type. Constraints are defined with the where clause.
public class MyGeneric<T> where T : IComparable<T> { private List<T> list = new List<T>(); public void Add(T item) { list.Add(item); } public void Sort() { list.Sort(); } }
Defining a generic type with C++/CLI is similar to defining a template with C++. Instead of the template keyword, with generics the generic keyword is used. The where clause is similar to that in C#; however, C++/CLI does not support a constructor constraint.
generic <typename T> where T : IComparable<T> ref class MyGeneric { private: List<T>^ list; public: MyGeneric() { list = gcnew List<T>(); } void Add(T item) { list->Add(item); } void Sort() { list->Sort(); } };
Visual Basic defines a generic class with the Of keyword. Constraints can be defined with As.
Public Class MyGeneric(Of T As IComparable(Of T)) Private myList = New List(Of T) Public Sub Add(ByVal item As T) myList.Add(item) End Sub Public Sub Sort() myList.Sort() End Sub End Class