CSharp examples for System:Array Index
Reverse the element of array between the startIndex and endIndex.
using System.Threading.Tasks; using System.Text; using System.Linq; using System.Diagnostics.Contracts; using System.Collections.Generic; using System;//from w w w. j a va 2 s .c o m public class Main{ /// <summary> /// Reverse the element of array between the startIndex and endIndex. /// </summary> /// <typeparam name="TElement"></typeparam> /// <param name="ary"></param> /// <param name="startIndex">zero-based start index</param> /// <param name="length">length to reverse</param> /// <exception cref="ArgumentNullException">array is null</exception> /// <exception cref="IndexOutOfRangeException"> startIndex or length less than zero, /// or startIndex plus length indicates a position out of range .</exception> public static void ReverseArray<TElement>(this TElement[] ary, int startIndex, int length) { if (ary == null) throw new ArgumentNullException(nameof(ary)); if (startIndex < 0) throw new IndexOutOfRangeException("startIndex less than zero"); if (length < 0) throw new IndexOutOfRangeException("length less than zero"); if (startIndex + length > ary.Length) throw new IndexOutOfRangeException("position out of range."); InternalReverseArray(ary, startIndex, length); } /// <summary> /// Reverse the element of array /// </summary> /// <typeparam name="TElement"></typeparam> /// <param name="ary"></param> /// <exception cref="ArgumentNullException">array is null</exception> public static void ReverseArray<TElement>(this TElement[] ary) { if (ary == null) throw new ArgumentNullException(nameof(ary)); InternalReverseArray(ary, 0, ary.Length); } internal static void InternalReverseArray<TElement>(TElement[] ary, int startIndex, int length) { Contract.Requires(ary != null); Contract.Requires(length >= 0); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex + length <= ary.Length); int endIndex = startIndex + length - 1; while (startIndex < endIndex) { TElement tmp = ary[startIndex]; ary[startIndex] = ary[endIndex]; ary[endIndex] = tmp; startIndex++; endIndex--; } } }