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


The SetValue() method sets a value to the element at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.

Firstly, set the array.

Array arr = Array.CreateInstance(typeof(String), 6);

No set values to the element using the SetValue() method.

arr.SetValue("One", 0);
arr.SetValue("Two", 1);
arr.SetValue("Three", 3);
arr.SetValue("Four", 4);
arr.SetValue("Five", 5);

The following is an example showing the usage of SetValue() method in C#.

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), 6);
         arr.SetValue("One", 0);
         arr.SetValue("Two", 1);
         arr.SetValue("Three", 3);
         arr.SetValue("Four", 4);
         arr.SetValue("Five", 5);
         Console.WriteLine("Length {0}",arr.GetLength(0).ToString());
         Console.ReadLine();
      }
   }
}

Output

Length 6

Updated on: 23-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements