C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
ExtensionAlso: 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
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] a = new int[]
{
1,
2,
3,
4,
5,
6,
7
};
foreach (int i in a.Slice(0, 1))
{
Console.WriteLine(i);
}
Console.WriteLine();
foreach (int i in a.Slice(0, 2))
{
Console.WriteLine(i);
}
Console.WriteLine();
foreach (int i in a.Slice(2, 5))
{
Console.WriteLine(i);
}
Console.WriteLine();
foreach (int i in a.Slice(2, -3))
{
Console.WriteLine(i);
}
}
}
public static class Extensions
{
/// <summary>
/// Get the array slice between the two indexes.
/// ... Inclusive for start index, exclusive for end index.
/// </summary>
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];
}
return res;
}
}
Output
1
1
2
3
4
5
3
4
Note: The Dev Codes thanks James and all contributors who notice errors on this site.
Strings: In my development efforts, I have also used string slice methods, which are proven equivalent in the main aspects to JavaScript.
String SliceInfo: The method's logic is equivalent to the string Slice method linked above, which I prove equivalent to the one in JavaScript.