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.
But I failed to find it. Any help is much appreciated.
ref int myInt = ref Unsafe.As<byte, int>(ref myBytes[index]). Do ensure though that aftermyBytes[index]there is enough space in your array to load a full size integer from (don't do out of bounds reads). It's basically the managed equivalent ofint* pMyInt = (int*)(pMyBytes + index).Unsafe, and anyway you don't need it. See my answer.Unsafe" - well, that depends on the use-case and the performance you want to achieve ;)MemoryMarshal.Castis just a wrapper aroundUnsafe.As(). Given that the OP just wanted to read a single element it feels weird to Cast the whole array to an int span first (though the JIT will probably optimize that away), but you'd still have the overhead of all the checks.