Array.CreateInstance
This C# method creates typed arrays. It does not require the type to be known at compile-time. It is a factory method.
When calling CreateInstance
in a C# program, we must specify the size of the target array. It returns a typed array of the specified size.
In the first section, we create a single-dimensional array of ints. In the second, we create a 2D array. To call Array.CreateInstance
, we must pass a Type pointer as the first argument.
typeof()
operator result.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)); } } }10 10 2
Why would we use Array.CreateInstance
? A program may not know the type of elements at compile-time. We could pass any Type reference to Array.CreateInstance
.
Array.CreateInstance
, we may need to perform some casting on the array returned. Consider the "is" and "as" casts.Array.CreateInstance
constructs arrays in memory using parameters. We do not need to know element types at compile-time. CreateInstance()
returns the abstract
base class
Array.