What are all the array initialization syntaxes that are possible with C#?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With