Search code examples
c#c++arrays.netienumerable

C# Passing array with specific array index


I want to pass an array to a function with specific index in C#, like we do in C++, something like below:

void foo(int* B) {
// do something;
}

int main() {
int A[10];
foo(A + 3);
}

In this case suppose A starts with base address 1000, then B would be 1000+(sizeof(int)*3). The answer in this link uses Skip() function call but in this case B should be of type IEnumerable<int> and on calling Skip() with ToArray() it creates a copy with different base address, but I want to pass this same array to function foo. How can we do that in C#?


Solution

  • This has been answered here: C# Array slice without copy

    You can use ArraySegment or Span to achieve this

    public static void Main()
    {
        int[] arr1 = new int[] {2, 5, 8, 10, 12};
        int[] arr2 = new int[] {10, 20, 30, 40};
    
        DoSomethingWithSegmentReference(new ArraySegment<int>(arr1, 2, arr1.Length - 2));
        
        DoSomethingWithSpanReference(arr2.AsSpan().Slice(1, arr2.Length - 1));
    }
    
    private static void DoSomethingWithSegmentReference(ArraySegment<int> slice){
        for(int i = 0; i < slice.Count; i++)
            slice[i] = slice[i] * 2;
    }
    
    private static void DoSomethingWithSpanReference(Span<int> slice){
        for(int i = 0; i < slice.Length; i++)
            slice[i] = slice[i] * 2;
    }