11 F# Interop

 

This chapter covers

  • Working with C# code and common .NET constructs
  • Consuming NuGet packages
  • Mixed-language solutions
  • JavaScript and F#

Just to reiterate, F# runs primarily on .NET—and a great deal of .NET, such as the base class library and most NuGet packages, is written in C#. This chapter shows you the techniques for how best to consume such code as well as how to write F# APIs that C# developers can more easily consume.

11.1 Working with other .NET code

You might have already realized this, but you already know how to consume C# from F#: pretty much the entire .NET framework class library is written in C#. This means that virtually all the APIs in the System namespace that are available out of the box are written in C#. F# has very good support for consuming such code, as we’ll see shortly.

11.1.1 Consuming C# classes

The language designers of F# went to a great deal of effort to try to make consuming C# from F# as easy as possible. You can create instances of classes, call methods on them, and work with mutable, imperative code. This means that F# developers can benefit from the entire .NET library ecosystem while still being able to write functional-first code. Figure 11.1 illustrates some of these features.

Figure 11.1 Illustrating the clear distinction between the object orientated (OO) and functional programming (FP) halves of F#

11.1.2 Interfaces

11.1.3 Fluent APIs

11.1.4 Tuples

11.1.5 Out parameters

11.1.6 Object-based programming

11.1.7 F# wrappers

11.2 Exposing F# to C#

11.2.1 Core F# concepts

11.2.2 Tips and tricks

11.2.3 Introducing F# into existing codebases