Array.CreateInstance MethodUse the Array.CreateInstance method to create arrays of a type known at runtime.
This page was last reviewed on Mar 26, 2022.
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.
Factory Pattern
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.
Typeof, nameof
So To create a one-dimensional array, only pass one integer after the type. To create a two-dimensional array, pass 2 integers.
2D Array
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.
Casting 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).
© 2007-2023 Sam Allen.