Chuyển đến nội dung

Bài 31 · Interop and Tooling

Interop with C# and .NET

Learn F# and C# interoperability: using .NET libraries from F#, null and out parameters, overloads and optional arguments, exposing F# code to C# callers, and mixing projects in one solution.

F# does not live in a separate world. It compiles to the same IL as C#, uses the same runtime, the same base class library and the same NuGet packages. You can call any .NET API from F#, and C# code can call your F# library. The friction is in the edges: nulls, mutable APIs, overloads and F#-only types like unions that C# callers see differently. This lesson maps those edges.

Calling .NET from F#

Open a namespace and use types as in C#:

FSHARP
open System
open System.Collections.Generic
open System.Text

let sb = StringBuilder()
sb.Append("Hello").Append(", ").Append("F#") |> ignore
printfn "%s" (sb.ToString())

let list = List<int>()           // System.Collections.Generic.List
list.Add 3
list.Add 1
list.Sort()
printfn "%A" (list |> Seq.toList)  // [1; 3]

Method calls use parentheses with arguments; |> ignore discards a return value you do not need (F# warns when a non-unit result is silently dropped). .NET collections work alongside F# ones, and conversions are cheap: Seq.toList, List.toArray, ResizeArray (an alias for List<'T>).

Out parameters become tuples

A method with an out parameter, such as Int32.TryParse, can be called with the out value omitted; the result is a tuple:

FSHARP
match Int32.TryParse "123" with
| true, n -> printfn "parsed %d" n
| false, _ -> printfn "bad number"

Named and optional arguments

FSHARP
let text = String.Join(separator = "-", values = [ "a"; "b"; "c" ])
let date = DateTime(year = 2026, month = 11, day = 12)

When overloads are ambiguous, add type annotations to the argument or name the parameters.

C# C# stand-in: the C# side of Int32.TryParse and StringBuilder

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Null at the boundary

F# types like records, unions and lists cannot be null. .NET types can. When a .NET method returns a reference that may be null, convert it immediately:

FSHARP
let env = Environment.GetEnvironmentVariable "HOME" |> Option.ofObj
FSHARP
// F# 9, with <Nullable>enable</Nullable> in the project file
let safeLength (s: string | null) =
    match s with
    | null -> 0
    | s -> s.Length

With F# 9's opt-in nullable reference types (<Nullable>enable</Nullable> in the project file) the compiler tracks string | null and warns about unsafe use, much like C#. Without it, treat every value that crosses from a .NET API as possibly null and use Option.ofObj or isNull.

Consuming F# from C#

Rules that make an F# library pleasant for C# callers:

  • Modules become static classes; functions become static methods. Curried functions (let add a b) appear to C# as a method with two parameters, and extra-curried parameter lists work fine. Functions taking tuples (let add (a, b)) are friendlier when you want a normal C# signature.
  • Records become classes with read-only properties and a constructor. Discriminated unions become an abstract class with nested subclasses; C# callers see Shape.Circle with Item properties, which is clumsy. Expose operations on unions through functions or members instead of making C# callers match them.
  • Option appears as FSharpOption<T>; list as FSharpList<T>. Public APIs aimed at C# should prefer IReadOnlyList<T>, IEnumerable<T> and Nullable or plain nulls (convert at the edge with Option.toObj).
  • Functions as values become FSharpFunc<A,B>. For C# callbacks accept Func<A,B> and Action<A> and convert.
  • Async is FSharpAsync<T>; expose Task<T> instead with Async.StartAsTask or write the member with task { }.
FSHARP
namespace Shapes

type Calculator() =
    // Tupled argument: C# sees Add(int a, int b)
    member _.Add(a: int, b: int) = a + b

    // Task-returning: C# can await it
    member _.AddLaterAsync(a: int, b: int) =
        task {
            do! System.Threading.Tasks.Task.Delay 10
            return a + b
        }

    // Option exposed as nullable for C#
    member _.TryParse(text: string) : System.Nullable<int> =
        match System.Int32.TryParse text with
        | true, n -> System.Nullable n
        | _ -> System.Nullable()
C#
// C#
var calc = new Shapes.Calculator();
int five = calc.Add(2, 3);
int later = await calc.AddLaterAsync(2, 3);
int? parsed = calc.TryParse("12");

Tip: in the project file, add <GenerateDocumentationFile>true</GenerateDocumentationFile> and keep the public surface small and C#-friendly, hiding F#-specific types inside the library.

Mixed solutions and project references

A solution can hold F# and C# projects side by side, and they reference each other as usual (dotnet add reference). F# projects, however, have two special rules that C# programmers trip over:

  1. File order matters. Files compile top to bottom, listed in the .fsproj, and a file can use only what appears above it. This forbids circular dependencies by construction.
  2. Interfaces and abstract classes defined in a C# project can be implemented by F# classes (and vice versa), so a C# web host with F# business logic is a perfectly normal architecture.
flowchart TD
    W["C# web host<br/>(ASP.NET Core)"] --> D["F# domain library<br/>records, unions, rules"]
    W --> I["C# infrastructure<br/>EF Core, HTTP clients"]
    I --> D
    D --> F["FSharp.Core"]

A common layout: the pure domain model in F#, the framework-heavy edges in whatever language fits.

C# C# stand-in: what an F# record looks like to a C# caller

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Using NuGet packages

Any NuGet package works from F#: dotnet add package Newtonsoft.Json. Some libraries are written in an idiom that feels odd in F# (heavy use of null, fluent builders, Action<T> callbacks). F# automatically converts a lambda to a Func or Action when passing to a .NET method, so list.ForEach(fun x -> printfn "%d" x) works. For popular libraries, check whether an F#-friendly wrapper exists (Fantomas for formatting, Giraffe for web, FsToolkit.ErrorHandling for results). See Projects, Packages and the dotnet CLI.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. How does F# let you call a method with an out parameter such as Int32.TryParse?

    match Int32.TryParse s with | true, n -> ... uses the tuple form.
  2. 2. What should you do with a possibly-null reference returned from a .NET API?

    F# types cannot be null, so convert at the boundary and keep the rest of the code null-free.
  3. 3. Which return type is friendliest to C# callers of an F# async operation?

    C# can await a Task<T> directly; FSharpAsync<T> is an F#-specific type.
  4. 4. What is true about file order in an F# project?

    The ordering forbids circular dependencies and is controlled in the .fsproj.

Summary

  • F# uses every .NET library; out parameters become tuples and lambdas convert to delegates.
  • Convert nulls to options at the boundary, or enable F# 9 nullable reference types.
  • For C# callers expose tupled members, Task, standard collections and plain classes, not F# unions and options.
  • F# and C# projects mix freely in one solution; F# file order matters.

Next: Projects, Packages and the dotnet CLI

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.