GENERIC FUNCTIONS

Any method can be made generic by adding one or more type parameters to the method signature like this:

static void OutputThing<T>(T thing) {

  Console.WriteLine("Thing: {0}", thing);

}

T is the type variable in this example, and it is listed in angle brackets right after the method name. Once it has been declared that way, it can be used in place of a type in the parameter list and also within the method body. In the example, thing is simply passed in to the Console.WriteLine method, which accepts parameters of any type and calls their ToString method in order to format them for output. As mentioned before, the method doesn’t actually care about the element thing or its type; it just passes the value on to some other method to deal with.

Here’s a call to this function with a explicit type parameters:

OutputThing<string>("A string");

OutputThing<int>(42);

Using explicit type parameters means that the type is checked by both Visual Studio IntelliSense and the C# compiler. A call like the following would elicit an error message at compile time:

OutputThing<double>("Hello world");

Although the example is extremely simple, it demonstrates one of the purposes of generics: instead of using a parameter of type object, the type is mentioned explicitly in these calls, which enables strict checking.

At the same time, many programmers regard it as too much of a hassle to actually specify the type explicitly. The OutputThing method can also be called like this:

OutputThing("A ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects 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.