C# Array Slice, Get Elements Between IndexesImplement a Slice extension method on the Array type. Slice gets array elements between 2 indexes.
A slice of an array is a range of elements. By using extension methods and generics, we simplify and clarify array slices. This makes for more reusable and powerful code. We write and test an array slice method.Array
here we see a generic method, which is simply a C# method that can receive and return parameters of any type. Our Slice method here uses this ability to simulate the built-in slice functionality of Python and other languages.
Main: We see the new Slice extension method used. We are using an int array with seven values in it.
Slice 1: The first slice we take extracts the elements between 0 and 1, the first int.
Extensions: This class contains a public static method called Slice. It is an extension method, which means it uses "this" in its first parameter.Extension
Also: The other confusing part is the use of the letter T. The Type T is replaced by the C# compiler with any type you specify.
C# program that slices array
static void Main()
int a = new int
foreach (int i in a.Slice(0, 1))
foreach (int i in a.Slice(0, 2))
foreach (int i in a.Slice(2, 5))
foreach (int i in a.Slice(2, -3))
public static class Extensions
/// Get the array slice between the two indexes.
/// ... Inclusive for start index, exclusive for end index.
public static T Slice<T>(this T source, int start, int end)
// Handles negative ends.
if (end < 0)
end = source.Length + end;
int len = end - start;
// Return new array.
T res = new T[len];
for (int i = 0; i < len; i++)
res[i] = source[i + start];
When the letter T (or letters such as V and C) appears in brackets after a method name, you are using a generic method. The letter T is replaced with the type specified at the call site.Generic Class, Method
of the Slice method here had a serious bug that caused negative end parameters to be incorrectly handled. James Kolpack wrote in with a correction of the end computation and I added a test for that case.
Note: Dot Net Perls thanks James and all contributors who notice errors on this site.
Here we saw a generic array slice method that is also an extension method, combining several concepts from newer versions of the C# language. This is a rare case where an extension method is appropriate.
© 2007-2020 Sam Allen. Send bug reports to email@example.com.