I'm refactoring a library we currently use, and I'm faced with the following problem.
We used to have the following stuff :
class Blah
{
float[][] data;
public float[] GetDataReference(int index)
{
return data[index];
}
}
For various reasons, I have replaced this jagged array version with a 1 dimensionnal array version, concatenating inner arrays.
My question is : how can I still return a reference to a sub array of data
?
class Blah
{
float[] data;
int rows;
public float[] GetDataReference(int index)
{
// Return a reference data from offset i to offset j;
}
}
I was thinking that unsafe and pointers stuff may be of use, is it doable ?
No, you can't do this - but you should look at using ArraySegment
instead.
Note that an array object consists of metadata about its length etc and then the data itself. You can't create a slice of an existing array and still have the metadata next to the data, if you see what I mean - there'd have to be an extra level of indirection (which is what ArraySegment
provides).
(I'm slightly surprised that ArraySegment doesn't do more wrapping, e.g. by implementing IList<T>
, but there we go. It would be easy enough to create such a structure if you wanted to.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With