CSharp - Array Array.CreateInstance

Introduction

The easiest way to create and index arrays is via C#'s language constructs:

int[] myArray = { 1, 2, 3 };
int first = myArray [0];
int last = myArray [myArray.Length - 1];

You can instantiate an array dynamically by calling Array.CreateInstance.

You can specify element type and number of dimensions at runtime.

The GetValue and SetValue methods let you access elements in a dynamically created array:

// Create a string array 2 elements in length:
Array a = Array.CreateInstance (typeof(string), 2);
a.SetValue ("hi", 0);                             //  ? a[0] = "hi";
a.SetValue ("there", 1);                          //  ? a[1] = "there";
string s = (string) a.GetValue (0);               //  ? s = a[0];

// We can also cast to a C# array as follows:
string[] cSharpArray = (string[]) a;
string s2 = cSharpArray [0];

Zero-indexed arrays created dynamically can be cast to a C# array of a matching or compatible type.

GetValue and SetValue are useful when writing methods that can deal with an array of any type and rank.

For multi-dimensional arrays, they accept an array of indexers:

public object GetValue (params int[] indices)
public void   SetValue (object value, params int[] indices)

The following method prints the first element of any array, regardless of rank:

Demo

using System;
class MainClass/*from  w  ww. j  ava 2  s.  c  o m*/
{
    public static void Main(string[] args)
    {

        int[] oneD = { 1, 2, 3 };
        int[,] twoD = { { 5, 6 }, { 8, 9 } };

        WriteFirstValue(oneD);   // 1-dimensional; first value is 1
        WriteFirstValue(twoD);   // 2-dimensional; first value is 5

    }
    static void WriteFirstValue(Array a)
    {
        Console.Write(a.Rank + "-dimensional; ");
        int[] indexers = new int[a.Rank];
        Console.WriteLine("First value is " + a.GetValue(indexers));
    }
}

Result