What are all the array initialization syntaxes that are possible with C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
The array creation syntaxes in C# that are expressions are:
In the first one, the size may be any non-negative integral value and the array elements are initialized to the default values.
In the second one, the size must be a constant and the number of elements given must match. There must be an implicit conversion from the given elements to the given array element type.
In the third one, the elements must be implicitly convertible to the element type, and the size is determined from the number of elements given.
In the fourth one the type of the array element is inferred by computing the best type, if there is one, of all the given elements that have types. All the elements must be implicitly convertible to that type. The size is determined from the number of elements given. This syntax was introduced in C# 3.0.
There is also a syntax which may only be used in a declaration:
The elements must be implicitly convertible to the element type. The size is determined from the number of elements given.
I refer you to C# 4.0 specification, section 7.6.10.4 "Array Creation Expressions".
Non-empty arrays
var data0 = new int[3]
var data1 = new int[3] { 1, 2, 3 }
var data2 = new int[] { 1, 2, 3 }
var data3 = new[] { 1, 2, 3 }
var data4 = { 1, 2, 3 }
is not compilable. Useint[] data5 = { 1, 2, 3 }
instead.Empty arrays
var data6 = new int[0]
var data7 = new int[] { }
var data8 = new [] { }
andint[] data9 = new [] { }
are not compilable.var data10 = { }
is not compilable. Useint[] data11 = { }
instead.As an argument of a method
Only expressions that can be assigned with the
var
keyword can be passed as arguments.Foo(new int[2])
Foo(new int[2] { 1, 2 })
Foo(new int[] { 1, 2 })
Foo(new[] { 1, 2 })
Foo({ 1, 2 })
is not compilableFoo(new int[0])
Foo(new int[] { })
Foo({})
is not compilableThese 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 asYou can also create dynamic arrays i.e. you can first ask the size of the array from the user before creating it.
Trivial solution with expressions. Note that with NewArrayInit you can create just one-dimensional array.