Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible array initialization syntaxes

What are all the array initialization syntaxes that are possible with C#?

like image 797
Joshua Girard Avatar asked Apr 15 '11 14:04

Joshua Girard


People also ask

How many ways we can initialize array?

There are two ways you can declare and initialize an array in Java. The first is with the new keyword, where you have to initialize the values one by one. The second is by putting the values in curly braces.

What are the types of array initialization?

There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.

How do you initialize all array elements?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

Which of the following is correct initialization of an array?

Correct option is option(a) int num[6] = { 2, 4, 12, 5, 45, 5 }; The correct way to declare an array is that the first word is the data types of the array then the second word is the name of the array followed by the square brackets.


1 Answers

These are the current declaration and initialization methods for a simple array.

string[] array = new string[2]; // creates array of length 2, default values string[] array = new string[] { "A", "B" }; // creates populated array of length 2 string[] array = { "A" , "B" }; // creates populated array of length 2 string[] array = new[] { "A", "B" }; // created populated array of length 2 

Note that other techniques of obtaining arrays exist, such as the Linq ToArray() extensions on IEnumerable<T>.

Also note that in the declarations above, the first two could replace the string[] on the left with var (C# 3+), as the information on the right is enough to infer the proper type. The third line must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. The fourth could also use inference. So if you're into the whole brevity thing, the above could be written as

var array = new string[2]; // creates array of length 2, default values var array = new string[] { "A", "B" }; // creates populated array of length 2 string[] array = { "A" , "B" }; // creates populated array of length 2 var array = new[] { "A", "B" }; // created populated array of length 2  
like image 105
Anthony Pegram Avatar answered Sep 22 '22 22:09

Anthony Pegram