Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a subarray reference in C# (using unsafe ?)

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 ?

like image 987
Wam Avatar asked Apr 08 '10 08:04

Wam


1 Answers

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

like image 197
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet