Array - WithinIndex
An Array extension method that check if the array is lower then the specified index.
public static void Main() { int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Display(numbers, 4); Display(numbers, 11); Display(numbers, 7); } public static void Display(Array array, int index) { // C# Extension Method: Array - WithinIndex if(array.WithinIndex(index)) { Console.WriteLine("{0} is within array index.", index); } else { Console.WriteLine("{0} is not within array index.", index); } }
View Source
using System; public static partial class Extensions { /// <summary> /// An Array extension method that check if the array is lower then the specified index. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="index">Zero-based index of the.</param> /// <returns>true if it succeeds, false if it fails.</returns> public static bool WithinIndex(this Array @this, int index) { return index >= 0 && index < @this.Length; } /// <summary> /// An Array extension method that check if the array is lower then the specified index. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="index">Zero-based index of the.</param> /// <param name="dimension">(Optional) the dimension.</param> /// <returns>true if it succeeds, false if it fails.</returns> public static bool WithinIndex(this Array @this, int index, int dimension = 0) { return index >= @this.GetLowerBound(dimension) && index <= @this.GetUpperBound(dimension); } }