TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Array.CreateInstance Method

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

Array.CreateInstance creates typed arrays.

It does not require the type to be known at compile-time. It is a factory method. When calling it we must specify the size of the target array.

Example. This program has 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.

Tip: You could pass a variable reference of type "Type" instead of the typeof() operator result.

Type ClassTypeof Operator

So: To create a one-dimensional array, only pass one integer after the type. To create a two-dimensional array, pass two integers.

C# program that uses Array.CreateInstance method

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

Discussion. 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.

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.

Summary. Array.CreateInstance is 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, Array.CreateInstance returns the abstract base class Array.

IsAs


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf