Chapter 10. Generics

WHAT'S IN THIS CHAPTER?

  • Understanding generics in F#

  • Using generic types

  • Applying type constraints

  • Working with statically resolved types

For the experienced C# or Visual Basic developer, this chapter will likely be simultaneously similar and yet maddeningly different from what's familiar in those languages. Generics have always played a key part in functional languages, thanks in large part due to the type inferenced nature of those languages, and as a result generics will be used far more often when writing F# code. This represents both a blessing and a curse: A blessing, in that code will often "silently" be more reusable and extensible than the C# or Visual Basic developer originally intended, but also a curse, in that some of the deeper and darker corners of generics and type systems, safely ignorable when writing object-oriented code, must now be confronted and programmers' demons slain.

BASICS

Normally, when developers write code, they use placeholders that will eventually contain values and manipulate those values in particular ways; we call those placeholders "variables" and, if those variables are part of a class instance, "fields." Generics, also known as parametric types, provide the ability for developers to write code using placeholders for the types of those variables or fields. Generics allow the compiler to continue to exercise full static type-checking, yet write classes that can be used with a variety of different types, all statically checked at ...

Get Professional F# 2.0 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.