-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
The current plan is to add ref fields as first class construct to the type system. See proposal at dotnet/csharplang#3936 for more details.
Original proposal
Overview
Make the System.ByReference<T> type (here) public instead of internal.
Rationale
It's already possible to achieve the same behavior of ByReference<T>, namely to store a ref T to some variable as a field in a ref struct, by leveraging the Span<T> and MemoryMarshal types, like so:
public readonly ref struct FakeByReference<T>
{
private readonly Span<T> span;
public ByReference(ref T value)
{
span = MemoryMarshal.CreateSpan(ref value, 1);
}
public ref T Value => ref MemoryMarshal.GetReference(span);
}This can either be used as is, as a field in some other ref struct type, or the same technique (storing a 1-length Span<T> in place of the missing ByReference<T> type) can be used in other ref struct types to reproduce this same behavior: storing a managed reference as a field in a ref struct type.
Given that this is already possible with existing APIs, as shown above, but it's less performant than the original ByReference<T>, more verbose and more error prone, why not just make the original ByReference<T> type public so everyone can use it with no need to reinvent the wheel?
It'd be a neat API to have, and at basically no cost, since it's already in the .NET Core BCL anyway. 😄