Chapter 8. Applied Object-Oriented Programming

This chapter could also be called “being functional in an object-oriented world.” By now you’ve mastered the F# syntax and style, but there is still plenty to be said about using F# in the object-oriented landscape of the .NET platform.

In this chapter, you learn how to create F# types that integrate better with other object-oriented languages like C#. For example, with operator overloading, you can allow your types to be used with symbolic code. Also, events enable your classes to notify consumers to receive notifications when certain actions occur. This not only enables you to be more expressive in your F# code, but also reduces the friction with non-F# developers when sharing your code.

Operators

A symbolic notation for manipulating objects can simplify your code by eliminating methods like Add and Remove, and instead using more intuitive counterparts like + and -. Also, if an object represents a collection of data, being able to index directly into it with the .[ ] or .[expr .. expr] notation can make it much easier to access the data an object holds.

Operator Overloading

Operator overloading is a term used for adding new meaning to an existing operator, like + or -. Instead of only working on primitive types, you can overload those operators to accept custom types you create. Operator overloading in F# can be done by simply adding a static method to a type. After that, you can use the operator as if it natively supported the type. The ...

Get Programming F# 3.0, 2nd Edition 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.