All possible array initialization syntaxes
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
How to initialize all members of an array to the same value?
Unless that value is 0 (in which case you can omit some part of the initializer
and the corresponding elements will be initialized to 0), there's no easy way.
Don't overlook the obvious solution, though:
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
Elements with missing values will be initialized to 0:
int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...
So this will initialize all elements to 0:
int myArray[10] = { 0 }; // all elements 0
In C++, an empty initialization list will also initialize every element to 0.
This is not allowed with C until C23:
int myArray[10] = {}; // all elements 0 in C++ and C23
Remember that objects with static storage duration will initialize to 0 if no
initializer is specified:
static int myArray[10]; // all elements 0
And that "0" doesn't necessarily mean "all-bits-zero", so using the above is
better and more portable than memset(). (Floating point values will be
initialized to +0, pointers to null value, etc.)
Different ways to Initialize an array
It's just syntactic sugar, the compiler still outputs the same newarr
cil instruction.
C++ array initialization
Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 }
is an idiomatic universal zero-initializer. This is also almost the case in C++.
Since this initalizer is universal, for bool
array you don't really need a different "syntax". 0
works as an initializer for bool
type as well, so
bool myBoolArray[ARRAY_SIZE] = { 0 };
is guaranteed to initialize the entire array with false
. As well as
char* myPtrArray[ARRAY_SIZE] = { 0 };
in guaranteed to initialize the whole array with null-pointers of type char *
.
If you believe it improves readability, you can certainly use
bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };
but the point is that = { 0 }
variant gives you exactly the same result.
However, in C++ = { 0 }
might not work for all types, like enum types, for example, which cannot be initialized with integral 0
. But C++ supports the shorter form
T myArray[ARRAY_SIZE] = {};
i.e. just an empty pair of {}
. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.
How to make inline array initialization work like e.g. Dictionary initialization?
The collection initializer syntax is translated into calls to Add
with the appropriate number of parameters:
var dict = new Dictionary<string,int>();
dict.Add("key1", 1);
dict.Add("key2", 2);
This special initializer syntax will also work on other classes that have an Add
method and implements IEnumerable
. Let's create a completely crazy class just to prove that there's nothing special about Dictionary
and that this syntax can work for any suitable class:
// Don't do this in production code!
class CrazyAdd : IEnumerable
{
public void Add(int x, int y, int z)
{
Console.WriteLine(x + y + z); // Well it *does* add...
}
public IEnumerator GetEnumerator() { throw new NotImplementedException(); }
}
Now you can write this:
var crazyAdd = new CrazyAdd
{
{1, 2, 3},
{4, 5, 6}
};
Outputs:
6
15
See it working online: ideone
As for the other types you asked about:
- It doesn't work on an array because it has no
Add
method. List<T>
has anAdd
method but it has only one parameter.
How to initialize an array in Java?
data[10] = {10,20,30,40,50,60,71,80,90,91};
The above is not correct (syntax error). It means you are assigning an array to data[10]
which can hold just an element.
If you want to initialize an array, try using Array Initializer:
int[] data = {10,20,30,40,50,60,71,80,90,91};
// or
int[] data;
data = new int[] {10,20,30,40,50,60,71,80,90,91};
Notice the difference between the two declarations. When assigning a new array to a declared variable, new
must be used.
Even if you correct the syntax, accessing data[10]
is still incorrect (You can only access data[0]
to data[9]
because index of arrays in Java is 0-based). Accessing data[10]
will throw an ArrayIndexOutOfBoundsException.
Related Topics
Is Is Possible to Export Functions from a C# Dll Like in VS C++
What Does the Unary Plus Operator Do
Why Does C# Not Provide the C++ Style 'Friend' Keyword
Is There a Difference Between "Throw" and "Throw Ex"
Creating a Blocking Queue≪T≫ in .Net
Using Cookiecontainer With Webclient Class
Input String Was Not in a Correct Format
Mvc5 Razor Html.Dropdownlistfor Set Selected When Value Is in Array
Convert Generic List/Enumerable to Datatable
Set Object Property Using Reflection
Is There a String Math Evaluator in .Net
How to Make the Script Wait/Sleep in a Simple Way in Unity
Use of Finalize/Dispose Method in C#
Best Way to Randomize an Array With .Net
What's the Use/Meaning of the @ Character in Variable Names in C#