© Mikael Olsson 2020
M. OlssonC# 8 Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-5577-3_28

28. Generics

Mikael Olsson1 
(1)
HAMMARLAND, Finland
 

Generics refer to the use of type parameters, which provide a way to design code templates that can operate with different data types. Specifically, it is possible to create generic methods, classes, interfaces, delegates, and events.

Generic Methods

In the following example, there is a method that swaps two integer arguments.
static void Swap(ref int a, ref int b)
{
  int temp = a;
  a = b;
  b = temp;
}
To make this into a generic method that can work with any data type, a type parameter first needs to be added after the method’s name, enclosed between angle brackets. The naming convention for type parameters ...

Get C# 8 Quick Syntax Reference: A Pocket Guide to the Language, APIs, and Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.