Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# System.Array How to Count or Find How Many Dimensions It Has?

If I have an unknown array as a System.Array, how can I find how many dimensions it has? I'm thinking of something that could be called like Array.GetDimensionCount()

For example if I am building an extension method on the System.Array class and I want to validate that the arrayDimensionIndex is not greater or equal than the number of dimensions the array has, I want to throw an ArgumentOutOfRangeException

    /// <summary>
    /// Determines whether the value of the specified arrayIndex is within 
    /// the bounds of this instance for the specified dimension.
    /// </summary>
    /// <param name="instance">The instance of the array to check.</param>
    /// <param name="arrayDimensionIndex">Index of the array dimension.</param>
    /// <param name="arrayIndex">The arrayIndex.</param>
    /// <returns></returns>
    /// <exception cref="System.ArgumentOutOfRangeException">
    /// If arrayDimensionIndex exceeds the number of dimesnions in the array.
    /// </exception>
    public static bool IsInBounds(this Array instance, int arrayDimensionIndex, int arrayIndex)
    {
        // Determine if this instance has more dimension than the specified array dimension to check.
        if(instance.Get?????() <= arrayDimensionIndex)
        {
            throw new ArgumentOutOfRangeException();
        }

        // Get the length of the dimension specifed
        int arraDimensionLength = instance.GetLength(arrayDimensionIndex);

        // Check if the value is withing the array bounds
        bool isInBounds = ((uint)arrayIndex < arraDimensionLength);

        // Return the result
        return isInBounds;
    }

Thanks.

like image 289
Dib Avatar asked Nov 06 '25 00:11

Dib


1 Answers

The key word you're looking for is Rank. Use the Rank property to find out how many dimensions your array has.

like image 147
Gabe Avatar answered Nov 07 '25 15:11

Gabe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!