Search code examples
f#ref-struct

How to define a ref struct in F# in .NET Standard 2.0?


When F# 4.5 was announced, it was stated that:

The F# feature set is comprised of

  • [...]

  • The ability to produce IsByRefLike structs (examples of such structs: Span<'T>and ReadOnlySpan<'T>).

How to "produce" these types? I tried the [<IsByRefLike>] attribute but is was not found in .NET Standard 2.0.


Solution

  • Starting with .NET SDK 6.0.200 (available in Visual Studio 2022 17.1), the F# compiler recognizes user-defined IsByRefLikeAttributes. The following code will transparently enable defining ref structs on .NET Standard 2.0 as well as later frameworks:

    #if NETSTANDARD2_0
    namespace System.Runtime.CompilerServices
    
    open System
    
    [<Sealed; AttributeUsage(AttributeTargets.Struct)>]
    type IsByrefLikeAttribute() = inherit Attribute()
    #endif
    
    namespace MyLibrary
    
    open System
    open System.Runtime.CompilerServices
    
    [<IsByRefLike>]
    type MyRefStruct(span: Span<int>) = struct end