Array length
In this chapter you will learn:
- What is the difference between array length and array rank
- How to get array length with GetLength function
- GetLength() and two dimension array
- How to get the last element in an array
Rank vs array
using System;// j a v a 2 s .c o m
class MainClass
{
static void Main()
{
int[] arr = new int[] { 15, 20, 5, 25, 10 };
Console.WriteLine("Rank = {0}, Length = {1}", arr.Rank, arr.Length);
}
}
The code above generates the following result.
Get array length with GetLength function
using System;/*java 2 s . co m*/
class MainClass
{
static void Main()
{
int[] arr = new int[] { 15, 20, 5, 25, 10 };
Console.WriteLine("GetLength(0) = {0}", arr.GetLength(0));
}
}
The code above generates the following result.
GetLength() and two dimension array
The following code uses the GetLength() method to get number of elements in each dimension of the two dimensional array.
using System;//from j a v a 2 s. co m
class MainClass
{
public static void Main()
{
string[,] names = {
{"J", "M", "P"},
{"S", "E", "S"},
{"C", "A", "W"},
{"G", "P", "J"},
};
int numberOfRows = names.GetLength(0);
int numberOfColumns = names.GetLength(1);
Console.WriteLine("Number of rows = " + numberOfRows);
Console.WriteLine("Number of columns = " + numberOfColumns);
}
}
The code above generates the following result.
Last element in an array
The following code uses the array length property to reference the last element in an array.
using System;/*from j a v a2 s . c o m*/
class MainClass
{
static void Main()
{
int[] arr = new int[] { 15, 20, 5, 25, 10 };
Console.WriteLine(arr[arr.Length-1]);
}
}
Next chapter...
What you will learn in the next chapter:
- Array Declaration with initialization
- How ro assign value to an array
- Set array element value by index(subscript)
- Index out of range exception
- What to do with IndexOutOfRangeException
Home » C# Tutorial » Array