How to use the GetValue() method of array class in C#?



The GetValue() method of array class in C# gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.

We have set the array values first using the Array.CreateInstance method.

Array arr = Array.CreateInstance(typeof(String), 3, 6);
arr.SetValue("One", 0, 0);
arr.SetValue("Two", 0, 1);
arr.SetValue("Three", 0, 2);
arr.SetValue("Four", 0, 3);
arr.SetValue("Five", 1, 4);
arr.SetValue("Six", 1, 5);
arr.SetValue("Seven", 1, 2);
arr.SetValue("Eight", 1, 3);

Then loop throught the array length. This will display all the values using the GetValue() method.

for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
Console.WriteLine( arr.GetValue(i, j));

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         Array arr = Array.CreateInstance(typeof(String), 3, 6);
         arr.SetValue("One", 0, 0);
         arr.SetValue("Two", 0, 1);
         arr.SetValue("Three", 0, 2);
         arr.SetValue("Four", 0, 3);
         arr.SetValue("Five", 1, 4);
         arr.SetValue("Six", 1, 5);
         arr.SetValue("Seven", 1, 2);
         arr.SetValue("Eight", 1, 3);
         int a = arr.GetLength(0);
         int b = arr.GetLength(1);
         // Getting values
         for (int i = 0; i <a; i++)
         for (int j = 0; j < b; j++)
         Console.WriteLine( arr.GetValue(i, j));
         Console.ReadLine();
      }
   }
}

Output

One
Two
Three
Four

Seven
Eight
Five
Six

Advertisements