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 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.