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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 26, 2022 (rewrite).