Here we develop a method in C# to match JavaScript. With the JavaScript slice method, you pass it the start index, which must always be 0 or higher.
using System;
class Program
{
static void Main()
{
Console.WriteLine(
"ABCDEF".Slice(1, 4));
Console.WriteLine(
"The morning is upon us.".Slice(3, -2));
string s =
"0123456789_";
// These slices are valid:
Console.WriteLine(s.Slice(0, 1));
// First char
Console.WriteLine(s.Slice(0, 2));
// First two chars
Console.WriteLine(s.Slice(1, 2));
// Second char
Console.WriteLine(s.Slice(8, 11));
// Last three chars
}
}
public static class Extensions
{
public static string Slice(this string source, int start, int end)
{
// Keep this for negative end support.
if (end < 0)
{
end = source.Length + end;
}
// Calculate length.
int len = end - start;
// Return Substring of length.
return source.Substring(start, len);
}
}
BCD
morning is upon u
0
01
1
89_