Ref Interfaces #8392
-
A lot of us are directly excited with Pseudo Exampleref interface IReader
{
public ReadOnlySpan<byte> ReadBytes(int count);
}
ref struct ReadOnlySpanReader(ReadOnlySpan<byte> span, ref int offset): IReader
{
public readonly ReadOnlySpan<byte> Span = span;
public readonly ref int Offset = offset;
public readonly ReadOnlySpan<byte> ReadBytes(int count)
{
ReadOnlySpan<byte> result = Span.Slice(offset, count);
offset += count;
return result;
}
}
class ReadOnlBufferReader(byte[] buffer, int offset): IReader
{
public readonly byte[] Buffer = buffer;
public int Offset = offset;
public ReadOnlySpan<byte> ReadBytes(int count)
{
ReadOnlySpan<byte> result = Buffer.AsSpan(offset, count);
offset += count;
return result;
}
} Pseudo Usage// Everything is all right
int ReadInt32(IReader reader)
{
return BinaryPrimitives.ReadInt32LittleEndian(reader.ReadBytes(sizeof(int)));
}
// Compiler error, ref struct may be part of the IReader
async Task<int> ReadInt32Async(IReader reader)
{
return BinaryPrimitives.ReadInt32LittleEndian(reader.ReadBytes(sizeof(int)));
} Interface Implementation ChainEvery |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
This is already implemented in latest C# compiler. See https://github.com/dotnet/csharplang/blob/main/proposals/ref-struct-interfaces.md . It's also already used in BCL. |
Beta Was this translation helpful? Give feedback.
-
Is a MySpan sp = new MySpan();
IRef spAsRef = (IRef)sp; // Compile error. Would require boxing.
public void DoThingWithIRef(IRef ref) { } // Compile error. Would require boxing.
public void DoThingWithIRefGenerically<TRef>(TRef ref) where TRef: IRef {} // Would work.
public ref interface IRef
{
string GetString();
}
public ref struct MySpan : IRef
{
public string GetString() => "Hey";
} |
Beta Was this translation helpful? Give feedback.
This is already implemented in latest C# compiler. See https://github.com/dotnet/csharplang/blob/main/proposals/ref-struct-interfaces.md . It's also already used in BCL.