C# – How to get int ref to byte[]

As the title says I need to get int reference into byte array

class ClassFoo {
    private byte[] _data;

    public ref byte GetByteRef(int index) {
        // ...Omitted for brevity
        return ref _data[index];
    }
    public ref int GetIntRef(int index) {
        // This won't work as it returns a integer value not reference
        return ref BitConverter.ToInt32(_data, index * 4);
    } 
}

I am positive that it is possible without switching into an unsafe context. And the answer is buried somewhere in documentation below.

  1. Span
  2. MemoryMarshal
  3. Unsafe

But I failed to find it. Any help is much appreciated.

>Solution :

First, you can use MemoryMarshal.Cast to convert a byte span to an int span. Since arrays are implicitly convertible to spans, you can just plug the array in there:

var intSpan = MemoryMarshal.Cast<byte, int>(_data);

And then you get a ref to the span’s index of your choice:

return ref intSpan[index];

Or, in one go:

return ref MemoryMarshal.Cast<byte, int>(_data)[index];

No pointer required.

Leave a Reply