Skip to content

OnixLabs.Core.IMemoryBinaryConvertible

matthew edited this page May 27, 2026 · 1 revision

IMemoryBinaryConvertible Interface

Defines a type that is convertible to an instance of ReadOnlyMemory<byte>.

Namespace OnixLabs.Core
Assembly OnixLabs.Core.dll (NuGet)

Definition

public interface IMemoryBinaryConvertible
{
    ReadOnlyMemory<byte> AsReadOnlyMemory();
}

Remarks

IMemoryBinaryConvertible exposes the underlying binary representation of a type as a ReadOnlyMemory<byte>. Unlike ReadOnlySpan<byte>, ReadOnlyMemory<byte> is an ordinary value type: it can be stored in fields, captured by lambdas, and flowed through async methods. This makes it the right choice wherever the span limitations apply — for example, when the binary data needs to be held beyond the current stack frame or passed across an await boundary.

A ReadOnlySpan<byte> can always be derived from a ReadOnlyMemory<byte> via its .Span property when synchronous, stack-based consumption is needed.

IBinaryConvertible composes this interface with ISpanBinaryConvertible. A type that implements IBinaryConvertible also satisfies IMemoryBinaryConvertible, so any API constrained to IMemoryBinaryConvertible accepts any binary-convertible type in the library.

Note Implementers typically hold an immutable backing byte[] and return a view over a defensive copy so that the caller cannot mutate the original data through the returned memory.

Examples

Implementing IMemoryBinaryConvertible

using System;
using OnixLabs.Core;

public sealed class ByteBuffer : IMemoryBinaryConvertible
{
    private readonly byte[] value;

    public ByteBuffer(ReadOnlySpan<byte> value)
    {
        this.value = value.ToArray();
    }

    // Returns a view over a defensive copy; the caller cannot corrupt backing data.
    public ReadOnlyMemory<byte> AsReadOnlyMemory() => value.ToArray();
}

Flowing binary data across async boundaries

ReadOnlyMemory<byte> can be captured and awaited, unlike ReadOnlySpan<byte>.

var buffer = new ByteBuffer([0x01, 0x02, 0x03]);

ReadOnlyMemory<byte> memory = buffer.AsReadOnlyMemory();
await WriteAsync(memory);

static async Task WriteAsync(ReadOnlyMemory<byte> data)
{
    // ReadOnlyMemory<byte> can be stored and captured across await; a span cannot.
    await Task.Yield();
    Console.WriteLine($"Wrote {data.Length} bytes.");

    // A span can still be obtained synchronously when needed.
    ReadOnlySpan<byte> span = data.Span;
}

Methods

Method Returns Description
AsReadOnlyMemory() ReadOnlyMemory<byte> Gets the current instance as a new ReadOnlyMemory<byte>.

AsReadOnlyMemory()

ReadOnlyMemory<byte> AsReadOnlyMemory();

Gets the current IMemoryBinaryConvertible instance as a new ReadOnlyMemory<byte> instance.

Returns — The current instance as a new ReadOnlyMemory<byte>.

See Also

ONIXLabs .NET Library


Clone this wiki locally