Generics are a form of parametric polymorphism found in a range of languages, including .NET languages, Java, Swift, Rust and Go (since 1.18).
generics is a language feature found in certain languages to enable a form of parametric-polymorphism. They typically allow the programmer to express concepts such as "A list of some type T" in a type-safe manner. Prior to the addition of generics to the java language and the .net clr, programmers using these languages were forced to downcast from the base Object
when using some general purpose classes, such as collection classes.
With the addition of generics, the programmer can instead use types such as List<int>
to create type-safe lists which only store int
objects.
In-depth detail for examples and concepts specifically for C# Generics is provided by Microsoft here. Information on Java generics can be found here.
Unlike c++ templates, generics are typically limited to simple type substitution, without the ability of templates to specialize in specific types (infamously misused in the C++ standard library in std::vector<bool>
which behaves radically different from any other std::vector<T>
). This also means that generics are not well suited for generic-programming, which typically relies on an ability to tailor generic algorithms for specific parameter types (again using a C++ example, pointers are usable with any generic algorithm expecting arguments to be iterators).
Java Generics Tutorials
.NET Generics Tutorials
Rust Generics Tutorials
Go Generics Tutorials
Example
C# without Generics
var list = new System.Collections.ArrayList();
list.Add(1);
list.Add("banana"); // will compile
int n = (int) list[0];
int s = (int) list[1]; // will compile, but throws an InvalidCastException
C# with Generics
var list = new System.Collections.Generic.List<int>();
list.Add(1);
//list.Add("banana"); -- Will not compile
int n = list[0];
//string s = list[1]; -- will not compile