C# Array.CreateInstance Method

Array type

You want to create an array that has elements of a certain type, which may not be known at compile-time, and also of a certain size. Using the Array.CreateInstance factory method, you can create arrays using a Type reference and some integers for the size.

Example

Note

This program is divided into two sections: in the first section, we create a single-dimensional array of integers; in the second, we create a two-dimensional array. To call Array.CreateInstance, you must pass a Type pointer as the first argument; you could pass a variable reference of type Type instead of the typeof() operator result. To create a one-dimensional array, only pass one integer after the type; to create a two-dimensional array, pass two integers.

Type Class Typeof Operator

This C# example program uses the Array.CreateInstance method.

Program that uses Array.CreateInstance method [C#]

using System;

class Program
{
    static void Main()
    {
	// [1] Create a one-dimensional array of integers.
	{
	    Array array = Array.CreateInstance(typeof(int), 10);
	    int[] values = (int[])array;
	    Console.WriteLine(values.Length);
	}
	// [2] Create a two-dimensional array of bools.
	{
	    Array array = Array.CreateInstance(typeof(bool), 10, 2);
	    bool[,] values = (bool[,])array;
	    values[0, 0] = true;
	    Console.WriteLine(values.GetLength(0));
	    Console.WriteLine(values.GetLength(1));
	}
    }
}

Output

10
10
2
2D Array Examples

Why?

Question and answer

So why would you want to ever use the Array.CreateInstance method? Perhaps your program does not know the type of elements you want to create an array of at compile-time. You could pass any Type reference to the Array.CreateInstance; this does not need to be statically determined by the C# compiler. With newer versions of the C# language, generic types have alleviated this requirement.

Summary

The Array.CreateInstance method provides a way to construct arrays in memory using parameters. You do not need to know at compile-time what type of array will be created. As a factory method, the Array.CreateInstance returns the abstract base class Array; you can cast this to a specific type of array.

Is Cast Example As Cast Example Array Types
.NET