CHAPTER 28

image

Generics

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 example below, 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 is that they should ...

Get C# Quick Syntax Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.