Generic Methods

Classes, structs, interfaces, and delegates (see Chapter 17) are not the only things that can be declared using generics. Methods can make use of generics, too. A generic method is simply a method that has one or more type parameters that can be used for its parameter types or return type.

Syntactically, the type parameter list is put between angle brackets in between the name of the method and the parameter list. A great source for generic method examples is in the LINQ extension methods defined on the Enumerable type defined in the System.Collection.Generic namespace. For example, here’s the Where method:

image

The method signature ...

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