There are already operators:
public static implicit operator ReadOnlySpan<T>(T[] array);
public static implicit operator Span<T>(T[] array);
Use case: have loaded data over a network and split (parsed) the data into tokens that you want to expose upstream with zero copies; have class:
public class Customer {
public Utf8String Name {get;}
public Utf8String Address {get;}
}
Here we can't store a Span<T> or a Utf8String directly as fields because of the stack-only semantics; but we could store the array-segments:
public class Customer {
private ArraySegment<byte> _name, _address;
public Utf8String Name => new Utf8String(new ReadOnlySpan<byte>(_name.Array, _name.Offset, _name.Count));
public Utf8String Address => new Utf8String(new ReadOnlySpan<byte>(_address.Array, _address.Offset, _address.Count));
}
With the addition of:
public static implicit operator ReadOnlySpan<T>(ArraySegment<T> segment);
public static implicit operator Span<T>(ArraySegment<T> segment);
this becomes much more convenient:
public class Customer {
private ArraySegment<byte> _name, _address;
public Utf8String Name => new Utf8String(_name);
public Utf8String Address => new Utf8String(_address);
}
This pairs quite nicely with the TryGetArrayElseGetPointer method which already exposes ArraySegment<byte> as part of the API surface.
Although it also prompts the question: should Utf8String also have operators for this type of scenario, for example:
public class Customer {
private ArraySegment<byte> _name, _address;
public Utf8String Name => _name;
public Utf8String Address => _address;
}
via:
public static implicit operator Utf8String(ArraySegment<byte> segment);
That might be a step too far, though.