Learn: What is the contrast between Length and GetLength() in C#, when and where they are utilized in the C# program?
In C#.Net, Length and GetLength() are essentially utilized with the exhibits, the greater part of the occasions these two things are mistaking for the designers. In this post, we will realize what is the distinction between Length and GetLength() in C#? When and where they ought to be utilized?
Length is a property which determines the all outnumber of components in the exhibit. While GetLength() is a pre-characterize technique for Array class. It has a contention which indicates the measurement.
In the event that we pass 0 to GetLenth() strategy then it restores the size of the first measurement. Also, on the off chance that we pass 1 to GetLegnth() strategy then it restores the size of the second measurement.
Example of Length Property
using System;
namespace arrayEx
{
class Program
{
static void Main(string[] args)
{
int i = 0;
int[] X;
X = new int[5];
Console.Write("Enter Elements : \n");
for (i = 0; i < X.Length; i++)
{
Console.Write("\tElement[" + i + "]: ");
X[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\n\nElements are: \n");
for (i = 0; i < X.Length; i++)
{
Console.WriteLine("\tElement[" + i + "]: "+X[i]);
}
}
}
}
In the announcement for (I = 0; I < X.Length; i++), we utilized X.Length property which is returning length of the exhibit that is 5.
Output:
Enter Elements :
Element[0]: 10
Element[1]: 20
Element[2]: 30
Element[3]: 40
Element[4]: 50
Elements are:
Element[0]: 10
Element[1]: 20
Element[2]: 30
Element[3]: 40
Element[4]: 50
Press any key to continue . . .
Example of GetLength() Method:
using System;
namespace arrayEx
{
class Program
{
static void Main(string[] args)
{
int i = 0;
int j = 0;
int[,] X;
X = new int[2,3];
Console.Write("Enter Elements : \n");
for (i = 0; i < X.GetLength(0); i++)
{
for (j = 0; j < X.GetLength(1); j++)
{
Console.Write("\tElement[" + i + ","+j+"]: ");
X[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.Write("\n\nElements are: \n");
for (i = 0; i < X.GetLength(0); i++)
{
for (j = 0; j < X.GetLength(1); j++)
{
Console.Write(X[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
Output:
Enter Elements :
Element[0,0]: 11
Element[0,1]: 22
Element[0,2]: 33
Element[1,0]: 44
Element[1,1]: 55
Element[1,2]: 66
Elements are:
11 22 33
44 55 66
Press any key to continue . . .
In above example GetLength(0) indicate number of lines and GetLength(1) determine number of segments.