F# · Lesson 11

.NET and C# interop

Use C# libraries from F# (named and optional arguments, overloads, null, Task and task { }, IDisposable, extension methods, interfaces, abstract classes, events, LINQ, System.Text.Json) and expose F# code that C# callers enjoy.

19 min read

In short

  • Convert once at the boundary; keep the core idiomatic
  • .NET methods take tuples; out parameters become tuples
  • Option.ofObj turns null into None
  • Consume Tasks in task { }; expose Task, never Async
  • Keep use inside the seq or task that needs it

Why this matters at work

On an F# team on .NET, almost every library you call was written in C#: ASP.NET Core, EF Core, the AWS, Azure or Google Cloud SDKs, Serilog, HttpClient, System.Text.Json. And the C# services next door will call your F# code. The F# you already know stays the same, but the boundary has its own rules: tupled method calls, null, Task, IDisposable, delegates and events, and serializers that don't know what a union is.

This topic is the phrasebook for that boundary. The rule of thumb behind all of it:

Speak C# at the edges, F# in the middle. Convert once, at the boundary, and keep the core free of null, exceptions-as-control-flow and mutable objects.

Calling .NET methods

.NET methods take their arguments as one tuple: String.Join(", ", names). On top of that, F# understands the extra calling features C# methods have:

▶ Try
open System
open System.Globalization
open System.Text

// Named arguments: clearer when there are several of the same type.
let sb = StringBuilder(capacity = 64)
sb.Append("order-").Append(value = 42) |> ignore    // fluent API: ignore the returned builder

// Settable properties can be set right in the constructor call, like a C# object initializer.
let uri = UriBuilder("https", "api.example.com", Port = 8443, Path = "/orders")
printfn "%s" (uri.Uri.ToString())                      // https://api.example.com:8443/orders

// `out` parameters come back as part of a tuple.
let parsed, date = DateTime.TryParseExact("2026-10-18", "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None)
printfn "%b %s" parsed (date.ToString "dd MMM yyyy")   // true 18 Oct 2026

// `params` arrays take any number of arguments.
printfn "%s" (String.Join(", ", "a", "b", "c"))        // a, b, c

// [<Flags>] enums combine with |||, F#'s bitwise or.
let tags = " api, billing ,,urgent ".Split(',', StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
printfn "%A" tags                                      // [|"api"; "billing"; "urgent"|]

In TypeScript you'd pass an options object (new Builder({ capacity: 64 })); named arguments are .NET's version of that. Optional parameters work the same way: a C# method declared as void Send(string to, string subject = "", bool urgent = false) can be called as mailer.Send("a@example.com") or mailer.Send("a@example.com", urgent = true), skipping the ones you don't need.

Overloads pick a behaviour, so pick deliberately

Many .NET methods have several overloads, and the one you choose can change the result, not just the syntax:

▶ Try
open System

printfn "%M" (Math.Round(2.345m, 2))                                   // 2.34 (!)
printfn "%M" (Math.Round(2.345m, 2, MidpointRounding.AwayFromZero))    // 2.35
printfn "%M" (Math.Round 2.5m)                                         // 2

Math.Round uses banker's rounding by default (a midpoint goes to the even neighbour), which surprises everyone the first time an invoice is off by a cent. JavaScript's Math.round(2.5) is 3. For money, pass the MidpointRounding you mean.

The compiler chooses an overload from the argument types, so it needs to know them. If you see "A unique overload for method 'X' could not be determined", add a type annotation to the lambda or value you pass.

Methods as functions

A .NET method can be passed where an F# function is expected, as long as it isn't ambiguous:

▶ Try
open System.IO

printfn "%A" ([ "src/app.fs"; "docs/readme.md" ] |> List.map Path.GetFileName)   // ["app.fs"; "readme.md"]
printfn "%A" ([ -1.5; 2.0 ] |> List.map System.Math.Abs)                          // [1.5; 2.0]: the float overload

Methods are not curried, though: you can't write text.Replace("a") and supply the second argument later. Wrap it in a lambda: fun (s: string) -> s.Replace("a", "b").

null at the boundary

F# code can't set a record, union or list to null. An option's None is stored as null at runtime, but F# never lets you write or test it that way. C# APIs can return null any time, so convert as soon as a value crosses into F#:

From .NETInto F#And back out
a reference that may be nullOption.ofObj xOption.toObj opt
a Nullable<int> (int? in C#)Option.ofNullable xOption.toNullable opt
▶ Try
open System

let tryEnv (name: string) : string option =
    Environment.GetEnvironmentVariable name |> Option.ofObj   // null when the variable isn't set

let describe (value: string) : string =
    match value with
    | null -> "missing"          // matching on null works for .NET types like string
    | text -> $"'{text}'"

printfn "%A" (tryEnv "SURELY_NOT_SET_ANYWHERE")   // None
printfn "%s %s" (describe null) (describe "ok")    // missing 'ok'
printfn "%A" (Option.ofNullable (Nullable 42))     // Some 42

When C# hands null to an F# type

A C# caller doesn't know your record can't be null, and nothing stops it from passing null (deserializers can produce one too). F# won't even let you write the check the obvious way:

▶ Try
type Order = { Id: int }

// if order = null then ...      error FS0043: The type 'Order' does not have 'null' as a proper value
let isMissing (order: Order) : bool = isNull (box order)   // box it to obj first, then check

printfn "%b %b" (isMissing Unchecked.defaultof<Order>) (isMissing { Id = 1 })   // true false

Do that check only in the methods C# calls (the public facade), never all over the core.

Two attributes adjust F# types for C#-style code:

  • [<AllowNullLiteral>] on a class or interface lets F# code use null for it. Use it for types that really are "maybe there" in a C# API, such as an EF Core entity that FindAsync returns as null.
  • [<CLIMutable>] on a record adds a parameterless constructor and property setters (F# code still sees an immutable record). Some libraries create objects that way: they make an empty object, then set its properties.
▶ Try
[<AllowNullLiteral>]
type CustomerEntity() =                  // shaped like an EF Core entity
    member val Id = 0 with get, set
    member val Email: string = null with get, set

let found: CustomerEntity = null         // allowed because of [<AllowNullLiteral>]
let email = found |> Option.ofObj |> Option.bind (fun c -> Option.ofObj c.Email)
printfn "%A" email                        // None

Nullable reference types (F# 9 and later)

Since F# 9, F# can track nulls in the type system, like C#'s nullable reference types. You turn it on per project with <Nullable>enable</Nullable> in the .fsproj. Then string means "never null" and string | null means "might be null", and the .NET libraries' own annotations flow in: Environment.GetEnvironmentVariable returns string | null, so passing it straight to a function that wants a string gives a nullness warning.

▶ Try
let shout (text: string | null) : string =
    match text with
    | null -> "(nothing)"
    | text -> text.ToUpper()        // `text` is a plain string here

printfn "%s %s" (shout null) (shout "hi")   // (nothing) HI

The syntax compiles without the setting too (you just don't get the warnings). It doesn't replace Option in your domain: it makes the boundary safer, because the compiler now points at every place a C# null can leak in. Your team's projects decide whether it's on; you'll see | null in signatures if it is.

Task, Async and task { }

The Computation Expressions topic covers async { } (cold) and task { } (hot). At the boundary the rules are simple:

  • .NET APIs return Task<'T>, Task or ValueTask<'T>. Consume them in task { } with let! and do!.
  • CancellationTokens are passed explicitly, as in C#. (async { } passes one along implicitly instead.)
  • Convert when you need to: Async.AwaitTask t turns a Task into an Async, and Async.StartAsTask(work, cancellationToken = ct) runs an Async as a Task.
  • Expose Task<'T> to C#, never Async<'T>. C# can't await an FSharpAsync<T>.
▶ Try
open System.Threading
open System.Threading.Tasks

let slowPrice (sku: string) : Async<decimal> =
    async {
        do! Async.Sleep 1000
        return 9.99m
    }

let priceForCSharp (sku: string) (ct: CancellationToken) : Task<decimal> =
    Async.StartAsTask(slowPrice sku, cancellationToken = ct)

let saveAll (save: string -> Task) (skus: string list) : Task<int> =
    task {
        for sku in skus do
            do! save sku                 // `do!` awaits a non-generic Task (or a ValueTask)
        return List.length skus
    }

let run () =
    let cts = new CancellationTokenSource(50)
    try
        (priceForCSharp "KB" cts.Token).Wait()
    with :? System.AggregateException as e ->
        printfn "%s" (e.InnerException.GetType().Name)   // TaskCanceledException

    printfn "%d" (saveAll (fun _ -> Task.CompletedTask) [ "KB"; "MS" ]).Result   // 2

run ()

A task { } with no return value has type Task<unit>. That is a Task (it derives from it), so C# can await it, and an interface member typed Task accepts it after an upcast: task { ... } :> Task.

IDisposable and use

use is C#'s using var: the value is disposed when it goes out of scope, even if an exception is thrown. The Modules and Classes topic introduced it; at the boundary there are two traps.

Trap 1: the work outlives the use. use disposes when the function returns. If the function returns a lazy seq or a running task, the work may still need the resource:

▶ Try
open System.IO

let readLinesBroken (text: string) : seq<string> =
    use reader = new StringReader(text)       // disposed when this function returns...
    seq {
        let mutable line = reader.ReadLine()  // ...but this only runs later, when someone enumerates
        while not (isNull line) do
            yield line
            line <- reader.ReadLine()
    }

let readLines (text: string) : seq<string> =
    seq {
        use reader = new StringReader(text)   // inside the seq: disposed when enumeration ends
        let mutable line = reader.ReadLine()
        while not (isNull line) do
            yield line
            line <- reader.ReadLine()
    }

try
    readLinesBroken "a\nb" |> List.ofSeq |> ignore
with ex ->
    printfn "%s" (ex.GetType().Name)          // ObjectDisposedException

printfn "%A" (readLines "a\nb" |> List.ofSeq) // ["a"; "b"]

The same goes for task { }: put the use inside the task block, so it's disposed after the last let!. A use written before task { disposes as soon as the task hits its first real await.

Trap 2: forgetting use on short-lived scopes. Many APIs return an IDisposable that marks a scope rather than a resource: logger.BeginScope(...), activitySource.StartActivity(...), a lock handle. use _ = ... keeps the scope open until the end of the block.

In task { }, use calls Dispose. Async-disposable .NET types (streams, DbContext, ServiceProvider) also implement IDisposable, so use works with them. A type that implements only IAsyncDisposable is rejected (as of F# 10), so you await x.DisposeAsync() yourself when you're done with it. Note that use at the top level of a script is just let (warning FS0524); in real code it always sits inside a function.

Extension methods

C# libraries add methods to existing types with extension methods. You get them by opening their namespace, the same as a C# using:

▶ Try
open System.Linq   // brings Where, Select, OrderBy, ... onto every sequence

let names = [ "ada"; "grace"; "alan" ]
let result = names.Where(fun n -> n.StartsWith "a").Select(fun n -> n.ToUpper()).ToList()
printfn "%A" (List.ofSeq result)   // ["ADA"; "ALAN"]

F# has two ways to add members of its own:

▶ Try
open System
open System.Runtime.CompilerServices

// 1. An F# type extension: nice in F#, invisible to C#.
type String with
    member s.IsBlank = String.IsNullOrWhiteSpace s

// 2. A C#-style extension method: works in F# and C#.
[<Extension>]
type StringExtensions =
    [<Extension>]
    static member ToSlug(s: string) : string = s.Trim().ToLowerInvariant().Replace(" ", "-")

printfn "%b %s" ("  ".IsBlank) ("Order History ".ToSlug())   // true order-history

Use the first for F#-only helpers and the second when a C# project will call them.

Implementing C# interfaces and abstract classes

Frameworks ask you to plug in implementations: an IComparer<T>, an IHostedService, a JsonConverter<T>, a DelegatingHandler. An object expression is the quickest way for interfaces:

▶ Try
open System
open System.Collections.Generic

// A case-insensitive dictionary for HTTP header names.
let headers = Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
headers["Content-Type"] <- "application/json"
printfn "%b" (headers.ContainsKey "content-type")   // true

let byLength =
    { new IComparer<string> with
        member _.Compare(a, b) = compare a.Length b.Length }

let sorted = List<string>([ "ccc"; "a"; "bb" ])
sorted.Sort(byLength)
printfn "%A" (List.ofSeq sorted)                    // ["a"; "bb"; "ccc"]

Abstract classes need a class that inherits the base and overrides its abstract members. TextWriter is a real one from the BCL (Console.Out is a TextWriter): you only have to provide Encoding and Write(char).

▶ Try
open System.IO
open System.Text

type UpperCaseWriter(inner: TextWriter) =
    inherit TextWriter()

    override _.Encoding = inner.Encoding
    override _.Write(c: char) = inner.Write(System.Char.ToUpperInvariant c)

let output = new StringWriter()
let writer = new UpperCaseWriter(output)
writer.Write("shipped ")          // TextWriter's own Write(string) calls our Write(char) per character
writer.WriteLine(42)
printfn "%s" (output.ToString().Trim())   // SHIPPED 42
  • inherit Base(args) calls the base constructor. base.Method(...) calls the base implementation.
  • override replaces an abstract or virtual member. In your own F# base classes, abstract declares a member and default gives it a virtual implementation.
  • Interface members are explicit in F#, so on a class you call them through the interface: (myComparer :> IComparer<string>).Compare(a, b). Abstract class members don't need that.

Delegates and events

C# APIs take callbacks as delegates: Func<T, TResult>, Action<T>, Predicate<T>, EventHandler<T>. When you pass a lambda (or a function) straight to a method that expects one, F# converts it for you, which is why names.Where(fun n -> ...) works. Elsewhere, such as a let value, a record field or a list of handlers, build the delegate yourself. (Recent compilers also accept a named function there, as in let p: Func<int, bool> = isEven, but not a lambda, so the explicit form is the one to remember.)

▶ Try
open System

let isAdult = Func<int, bool>(fun age -> age >= 18)   // an explicit delegate value
printfn "%b" (isAdult.Invoke 20)                     // true

You need this for APIs whose parameter is the base type Delegate (ASP.NET Core minimal APIs: app.MapGet("/", Func<string>(fun () -> "ok"))), because there's no specific delegate type to convert to.

.NET events are how C# classes say "something happened". Subscribing looks like this:

▶ Try
open System

type PriceChangedArgs(sku: string, price: decimal) =
    inherit EventArgs()
    member _.Sku = sku
    member _.Price = price

type PriceList() =
    let priceChanged = Event<EventHandler<PriceChangedArgs>, PriceChangedArgs>()

    [<CLIEvent>]                                 // compile as a real .NET event, so C# can use +=
    member _.PriceChanged = priceChanged.Publish

    member this.SetPrice(sku: string, price: decimal) =
        priceChanged.Trigger(this, PriceChangedArgs(sku, price))

let prices = PriceList()
prices.PriceChanged.Add(fun args -> printfn "F# saw %s = %M" args.Sku args.Price)

let handler = EventHandler<PriceChangedArgs>(fun _sender args -> printfn "handler saw %s" args.Sku)
prices.PriceChanged.AddHandler handler      // C#: prices.PriceChanged += handler
prices.SetPrice("KB", 49m)
prices.PriceChanged.RemoveHandler handler   // C#: prices.PriceChanged -= handler
prices.SetPrice("KB", 45m)                  // only the F# subscriber runs now
  • Event<'Delegate, 'Args> plus [<CLIEvent>] gives C# callers a normal event. Without the attribute, C# sees a property of type IEvent<...> instead.
  • .Add subscribes for good. AddHandler/RemoveHandler let you unsubscribe, and an event is also an IObservable, so Observable.filter/Observable.subscribe work and subscribe returns an IDisposable to unsubscribe. Forgetting to unsubscribe from a long-lived object is the classic .NET memory leak.

LINQ from F#

LINQ methods work from F# (above), but for in-memory data the List, Seq and Array modules are the F# way and read better in pipelines. LINQ matters for IQueryable, where the query is translated to SQL by EF Core or to another query language by a LINQ provider:

▶ Try
open System.Linq

let orders = [ 120m; 35m; 900m ].AsQueryable()    // stands in for dbContext.Orders

let big = orders.Where(fun total -> total > 100m)  // F# lambdas become expression trees here
printfn "%s" (big.Expression.ToString())             // [120; 35; 900].Where(total => (total > 100))

let viaQuery =
    query {
        for total in orders do
        where (total > 100m)
        sortByDescending total
        select total
    }

printfn "%A" (List.ofSeq viaQuery)                   // [900M; 120M]

The trap: Seq functions on an IQueryable run in memory. dbContext.Orders |> Seq.filter (fun o -> ...) compiles fine, but it treats the table as a plain IEnumerable and streams every row into your process before filtering. Keep database queries in query { } or Queryable methods (.Where, .Select) until they're materialised, then switch to F# collections.

System.Text.Json with F# types

System.Text.Json (STJ) is what ASP.NET Core uses. It knows a fair amount of F# out of the box:

▶ Try
open System.Text.Json

type Customer = { Name: string; Nickname: string option; Tags: string list }

let web = JsonSerializerOptions(JsonSerializerDefaults.Web)   // camelCase, case-insensitive: what ASP.NET Core uses

let ada = { Name = "Ada"; Nickname = None; Tags = [ "vip" ] }
printfn "%s" (JsonSerializer.Serialize(ada, web))     // {"name":"Ada","nickname":null,"tags":["vip"]}

let bob = JsonSerializer.Deserialize<Customer>("""{"name":"Bob","nickname":"bobby","tags":[]}""", web)
printfn "%A" bob.Nickname                             // Some "bobby"

let partial = JsonSerializer.Deserialize<Customer>("""{"name":"Cy"}""", web)
printfn "%b" (isNull (box partial.Tags))              // true: a missing list is null, not []!
F# typeSTJ out of the box
records, anonymous recordsyes: properties out, constructor in
option, voptionyes: None is null, Some x is just x
list, Set, Map<string, _>, arraysyes: arrays and objects
tuplesas {"Item1": ..., "Item2": ...} (avoid in contracts)
unions, including single-case ones like OrderId of stringno: NotSupportedException

Two things to remember:

  • A missing property becomes null, even for a string or string list field that F# thinks can't be null. So JSON input is untrusted: validate it (the next topic) before it becomes a domain value.
  • Unions need help. Your options:
    1. DTOs: map the union to a plain record with a discriminator field (Type = "card") at the boundary. Works with any serializer and keeps the wire format separate from the domain. The usual choice for public APIs.
    2. A custom JsonConverter<'T>: an abstract class you inherit, good for small value types like OrderId.
    3. FSharp.SystemTextJson: a NuGet package whose JsonFSharpConverter handles unions, with options for the JSON shape.
// (not runnable here) FSharp.SystemTextJson is a NuGet package
open System.Text.Json
open System.Text.Json.Serialization

let options = JsonFSharpOptions.Default().WithUnionUnwrapFieldlessTags().ToJsonSerializerOptions()
// type Payment = Card of last4: string | Cash
// JsonSerializer.Serialize(Cash, options)          -> "Cash"
// JsonSerializer.Serialize(Card "4242", options)   -> {"Case":"Card","Fields":["4242"]}

// In ASP.NET Core:
// builder.Services.ConfigureHttpJsonOptions(fun o -> o.SerializerOptions.Converters.Add(JsonFSharpConverter()))

Exposing F# code to C# callers

C# can call any F# code, but some F# shapes look odd from the other side. This is what a C# developer sees:

F#C# seesFriendlier for C#
let add (a: int) (b: int) in a modulestatic int add(int a, int b) (fine)[<CompiledName("Add")>] for PascalCase
a parameter f: int -> intFSharpFunc<int, int>Func<int, int>
Async<'T>FSharpAsync<T> (can't await)Task<'T>
'T listFSharpList<T> (enumerable, but odd)IReadOnlyList<'T> or seq<'T>
'T optionFSharpOption<T> (and None arrives as null)null, a bool TryX(..., out x) method, or Nullable
member _.Send(?subject: string)a required FSharpOption<string> parameter[<Optional; DefaultParameterValue("")>]
a uniona class with IsCard, Tag, NewCard(...)fine for results; consider a C# switch-friendly shape
a recordan immutable class with a constructor and Equals(good as is)

The usual shape is a thin facade class in a namespace, written in C#'s terms, over the idiomatic F# modules:

// (not runnable here) a namespace needs a compiled project, not a script
namespace Example.Pricing

open System
open System.Collections.Generic
open System.Runtime.InteropServices
open System.Threading
open System.Threading.Tasks

type PricingService(getPrice: string -> Async<decimal option>) =
    member _.QuoteAsync(sku: string, quantity: int, [<Optional; DefaultParameterValue("")>] coupon: string,
                        [<Optional>] ct: CancellationToken) : Task<decimal> =
        Async.StartAsTask(Pricing.quote getPrice sku quantity (Option.ofObj coupon), cancellationToken = ct)

    member _.TryGetPrice(sku: string, [<Out>] price: byref<decimal>) : bool =
        match Pricing.tryCached sku with
        | Some p -> price <- p; true
        | None -> price <- 0m; false

    member _.Where(filter: Func<Product, bool>) : IReadOnlyList<Product> =
        Pricing.all () |> List.filter filter.Invoke |> ResizeArray :> IReadOnlyList<Product>
// C# (not runnable here)
var service = new PricingService(...);
decimal total = await service.QuoteAsync("KB", 2);         // optional coupon and token skipped
if (service.TryGetPrice("MS", out var price)) { /* ... */ }
var cheap = service.Where(p => p.Price < 10m);

On the F# side, [<Out>] price: byref<decimal> comes back as a tuple, as with any .NET method: let found, price = service.TryGetPrice "MS".

Common mistakes

  • Letting null past the boundary. Convert with Option.ofObj where the value arrives, not three layers later.
  • Math.Round and friends with the default overload for money. Say which rounding you want.
  • use outside a seq { } or task { } that still needs the resource. Move it inside the block.
  • Returning Async, F# lists, options or curried function parameters from an API C# will call. Write a facade.
  • Piping an IQueryable into Seq.filter: the database filter silently becomes an in-memory one.
  • Serializing unions or domain types directly with STJ. It throws for unions, and deserializing skips your validation. Use DTOs (next topic) or a converter.
  • Subscribing with .Add to a long-lived event from a short-lived object. Use AddHandler/RemoveHandler or dispose the Observable.subscribe result.

Cheat sheet

// (not runnable here) a summary, not a program
obj.Method(a, b)                         // tupled arguments
Ctor(capacity = 16, Port = 8443)         // named argument, property setter
let ok, value = Int32.TryParse "42"      // out parameters -> tuple
A.X ||| A.Y                              // combine [<Flags>] enums
Option.ofObj x / Option.toObj o          // null <-> option
Option.ofNullable n / Option.toNullable o
isNull (box record)                      // null check for an F# type from C#
[<AllowNullLiteral>] [<CLIMutable>]      // C#-friendly classes / records
task { let! x = t in return x }          // Task<'T>; put do! steps on their own lines
Async.StartAsTask(a, cancellationToken = ct) / Async.AwaitTask t
use x = new Thing()                      // dispose at end of scope (inside the CE!)
open System.Linq                         // extension methods
[<Extension>] static member ...          // C#-visible extension method
{ new IComparer<T> with member _.Compare(a, b) = ... }
inherit TextWriter() / override _.Encoding = ...   // in a class: subclass an abstract class
Func<int, bool>(fun x -> ...)            // explicit delegate
Event<Handler, Args>() + [<CLIEvent>]    // C#-visible event
query { for x in q do where (...); select x }
JsonSerializerOptions(JsonSerializerDefaults.Web)
[<Optional; DefaultParameterValue(..)>] / [<Out>] x: byref<T>

The exercises

  1. Calling .NET APIs: overloads, named arguments, out parameters and flags enums in a money and date helper.
  2. Null at the boundary: wrap a C#-style customer API that returns null and Nullable in options.
  3. Implement a C# repository interface: Task-returning members with task { }, cancellation and entities that can be null.
  4. JSON DTOs with System.Text.Json: serialize records with Web defaults and map a union through a DTO.
  5. A custom JsonConverter: inherit JsonConverter<'T> so STJ can read and write your domain value types.
  6. A C#-friendly facade: optional parameters, out parameters, Func, Task and a real .NET event over an F# module.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app