Method notes. 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.
Example. 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.
Tip We could pass a variable reference of type "Type" instead of the 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
A discussion. 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.
And This Type does not need to be statically determined (before execution) by the C# compiler.
Note With newer versions of the C# language, generic types have alleviated this requirement.
Detail For Array.CreateInstance, we may need to perform some casting on the array returned. Consider the "is" and "as" casts.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 26, 2022 (rewrite).