Chapter 4. Generics
In Chapter 3, I showed how to write types and described
the various kinds of members they can contain. However, there’s an extra
dimension to classes, structs, interfaces, and methods that I did not show.
They can define type parameters, which are placeholders
that let you plug in different types at compile time. This lets you write
just one type and then produce multiple versions of it. This is called a
generic type. For example, the class library defines a
generic class called List<T> that
acts as a variable-length array. T is a
type parameter here, and you can use any type as an argument, so List<int> is a list of integers, List<string> is a list of strings, and so
on. You can also write a generic method, which is a
method that has its own type arguments, independently of whether its
containing type is generic.
Generic types and methods are visually distinctive because they always
have angle brackets (< and >) after the name. These contain a
comma-separated list of parameters or arguments. The same parameter/argument
distinction applies here as with methods: the declaration specifies a list
of parameters, and then when you come to use the method or type, you supply
arguments for those parameters. So List<T> defines a single type parameter,
T, and List<int> supplies a type
argument, int, for that
parameter.
Type parameters can be called whatever you like, within the usual constraints for identifiers in C#. There’s a common but not universal convention of using ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access