In this article, we will discuss the Type.GetArrayRank in C# with its syntax and examples.
What is the Type.GetArrayRank method?
The Type.GetArrayRank function in C# is a reflection method from the System namespace . This function is part of the Type class, which is required for inspecting and using type metadata in the Common Language Runtime (CLR) . GetArrayRank is used to determine the rank (dimensionality) of an array.
Basics of C# Arrays
Arrays are basic data structures that hold items of the same type in adjacent memory regions. Arrays may be single-dimensional, multidimensional, or jagged. A single-dimensional array is basically a vector, but a multidimensional array may contain more than two dimensions.
Introduction to the Type Class
The Type class is part of the .NET Framework and contains an advanced set of methods for accessing type-related data at runtime. It is often used in reflection, which allows the computer to inspect and communicate with types dynamically.
The GetArrayRank function is specialized to array types. It helps us to identify the rank or number of dimensions of a specific array type. It is particularly useful when dealing with arrays of varied sizes, and the program must adjust its behavior appropriately.
Syntax:
It has the following syntax:
public virtual int GetArrayRank().
Return Value: This function returns an integer representing the number of dimensions in the present type.
Exception: This function throws an ArgumentException if the current type does not correspond to an array.
Example 1:
Let us take an example to illustrate the Type.GetArrayRank method in C#.
using System;
using System.Globalization;
using System.Reflection;
class ArrayRank{
// Main Method
public static void Main()
{
try
{
// the object type declaration
Type objtype = typeof(int[,,,,,,,]);
// value to store the dimension using GetArrayRank() method
int rankValue = objtype.GetArrayRank();
// print statement
Console.WriteLine("The ArrayRank is: {0}", rankValue);
}
catch (ArgumentException ex)
{
Console.WriteLine("The type is not in the given array");
Console.Write("The Exception is Thrown: ");
Console.Write("{0}", ex.GetType(), ex.Message);
}
}
}
Output:
The ArrayRank is: 8
Example 2:
Let us take another example to illustrate the Type.GetArrayRank method in C#.
using System;
using System.Globalization;
using System.Reflection;
class ArrayRank{
// Main Method
public static void Main()
{
try
{
// the object type declaration
Type objtype = typeof(int);
// value to store the dimension using GetArrayRank() method
int rankValue = objtype.GetArrayRank();
// print statement
Console.WriteLine("The ArrayRank is: {0}", rankValue);
}
catch (ArgumentException ex)
{
Console.WriteLine("The type is not in the given array");
Console.Write("The Exception is Thrown: ");
Console.Write("{0}", ex.GetType(), ex.Message);
}
}
}
Output:
The type is not in the given array
The Exception is Thrown: System.ArgumentException