tags:

views:

783

answers:

3

This is an easy one, I am sure, but I can't seem to find it on google.

If I have a function:

foo(int[] a) {}

and I want to call it with a subarray of an array:

for instance: myNums[3]+ (i.e. an array {4,5,6}), given myNums:
int[] myNums = { 1,2,3,4,5,6};

Of course, I don't want to create a new array of just those sub items. I certainly could just pass the array and the index, but then I would have to write all the function code with offsets...ugly.

So, how does one do this in C# (.NET 2.0)?

foo(&myNums[3]) is reporting unsafe.

foo(myNums[3]) won't work (it is passing just an int).

Do I need to map this to some kind of collection?

+2  A: 

Use LINQ extension methods:

int[] myNums = { 1,2,3,4,5,6 };

var subset = myNums.Skip(2).Take(2); //will contain 3,4

int[] subsetAsArray = myNums.Skip(2).Take(2).ToArray();

This assumes you are using .NET 3.0+. You'll also need to include System.Linq in your code file.

Rex M
Cool. However, I am bound to .NET 2.0..
This creates a copy, and he is specifically asking for an alias.
Pavel Minaev
http://www.albahari.com/nutshell/linqbridge.aspx (support for linq added as a reference that works in .net 2.0)
Nader Shirazie
+3  A: 

If you have a function exactly as defined (i.e. it takes an array), there's no way you can do this.

If you'd have a function that would take some collection interface instead, e.g.:

void foo(IList<int> a) { ... }

then you could pass an array to it, and you could also write your own IList<T> implementation that wraps a subrange of any other IList<T> (but there isn't a stock solution for this in FCL).

Pavel Minaev
I think this: "but there isn't a stock solution for this" is what I am looking for. That is too bad. Thanks.
+3  A: 

Passing the address of an array to a function is something not supported by C# out-of-the-box. Either you have to do it using unsafe method, the code will be C-like (though you need to compile with unsafe option). or you would have to code it the way managed code are ought to be, in this case, pass the offset.

    public Form1()
    {
        InitializeComponent();
        int[] a = { 4, 5, 6, 7, 8 };

        unsafe
        {
            fixed (int* c = a)
            {
                SubArrayPointer(c + 3);
            }
        }
        SubArray(a, 3);
    }

    unsafe void SubArrayPointer(int* d)
    {
        MessageBox.Show(string.Format("Using pointer, outputs 7 --> {0}", *d));
    }

    void SubArray(int[] d, int offset)
    {
        MessageBox.Show(string.Format("Using offset, outputs 7 --> {0}", d[offset]));
    }
Michael Buen