Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading