Lesson 27. Exposing F# types and functions to C#

 

In this unit (and indeed throughout this book), you’ve concentrated on how to consume C# from F#. But it’s common to also go the other way, and write libraries in F# and consume them in C#. For example, you might create a data access layer in F# underneath a C# GUI, or write a general-purpose NuGet package in F# that can be consumed in both C# and F#. This lesson covers the following:

  • F# data types
  • Namespaces and modules
  • F# functions
  • Gotchas when consuming F# code from C#

Even in an existing code base that’s mostly C#, you’ll still want to work with F# in some cases. We’ll cover more of this in the coming lessons, but it’s not that unusual—particularly when working on larger projects or with existing code bases. The following section provides some examples of interoperating between F# and C#.

27.1. Using F# types in C#

We’re fortunate that the F# team spent time looking at the situations that arise when exposing data created in F# to C#, because they’ve done a great job in nearly all common cases. As you’ll see, F# data types all boil down to primitives that you already know; it’s simply that the F# language allows us to work with those same primitives at a higher level. Let’s first look at the common F# data types we discussed in the first half of the book.

27.1.1. Records

27.2. More on F# interoperability

27.3. Summarizing F# to C# interoperability

Summary

sitemap