© Mikael Olsson 2018
Mikael OlssonC# 7 Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-3817-2_28

28. Generics

Mikael Olsson1 
(1)
Hammarland, Länsi-Suomi, 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 ...

Get C# 7 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.