What are all the array initialization syntaxes that are possible with C#?
C# – All possible array initialization syntaxes
array-initializationarrayscsyntax
Related Topic
- Javascript – How to check if an array includes a value in JavaScript
- Javascript – var functionName = function() {} vs function functionName() {}
- Javascript – Sort array of objects by string property value
- Javascript – What does “use strict” do in JavaScript, and what is the reasoning behind it
- Javascript – Get all unique values in a JavaScript array (remove duplicates)
- Javascript – How to check if an object is an array?
- Javascript – How to remove a specific item from an array
- Javascript – For-each over an array in JavaScript
Best Answer
These are the current declaration and initialization methods for a simple array.
Note that other techniques of obtaining arrays exist, such as the Linq
ToArray()
extensions onIEnumerable<T>
.Also note that in the declarations above, the first two could replace the
string[]
on the left withvar
(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