All possible array initialization syntaxes

755,142

Solution 1

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 

Solution 2

The array creation syntaxes in C# that are expressions are:

new int[3]
new int[3] { 10, 20, 30 }
new int[] { 10, 20, 30 }
new[] { 10, 20, 30 }

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:

int[] x = { 10, 20, 30 };

The elements must be implicitly convertible to the element type. The size is determined from the number of elements given.

there isn't an all-in-one guide

I refer you to C# 4.0 specification, section 7.6.10.4 "Array Creation Expressions".

Solution 3

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. Use int[] data5 = { 1, 2, 3 } instead.

Empty arrays

  • var data6 = new int[0]
  • var data7 = new int[] { }
  • var data8 = new [] { } and int[] data9 = new [] { } are not compilable.

  • var data10 = { } is not compilable. Use int[] 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 compilable
  • Foo(new int[0])
  • Foo(new int[] { })
  • Foo({}) is not compilable

Solution 4

Enumerable.Repeat(String.Empty, count).ToArray()

Will create array of empty strings repeated 'count' times. In case you want to initialize array with same yet special default element value. Careful with reference types, all elements will refer same object.

Solution 5

var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};
Share:
755,142
Joshua Girard
Author by

Joshua Girard

Updated on July 17, 2022

Comments

  • Joshua Girard
    Joshua Girard almost 2 years

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

  • BoltClock
    BoltClock about 13 years
    What is the new[] { ... } (or new { ... } for other types) syntax known as?
  • Eric Lippert
    Eric Lippert about 13 years
    @BoltClock: The first syntax you mention is an "implicitly typed array creation expression". The second is an "anonymous object creation expression". You do not list the other two similar syntaxes; they are "object initializer" and "collection initializer".
  • Jeffrey L Whitledge
    Jeffrey L Whitledge about 13 years
    Not exactly C# "syntax", but let's not forget (my personal favorite) Array.CreateInstance(typeof(int), 3)!
  • Brian
    Brian about 13 years
    @Jeffrey: If we're going down that road,it starts getting silly. E.g., "1,2,3,4".split(',').
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen about 11 years
    Then for multi-dimensional arrays, there exist "nested" notations like new int[,] { { 3, 7 }, { 103, 107 }, { 10003, 10007 }, };, and so on for int[,,], int[,,,], ...
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen about 10 years
    Yes, in var arr1 = Enumerable.Repeat(new object(), 10).ToArray(); you get 10 references to the same object. To create 10 distinct objects, you can use var arr2 = Enumerable.Repeat(/* dummy: */ false, 10).Select(x => new object()).ToArray(); or similar.
  • jpmc26
    jpmc26 over 8 years
    It would be good to more clearly separate the invalid syntaxes from the valid ones.
  • Learning-Overthinker-Confused
    Learning-Overthinker-Confused over 6 years
    @EricLippert:Is pure array or generic array like abc[] is faster than list because it is written in low level programming language?
  • Eric Lippert
    Eric Lippert over 6 years
    @Learning-Overthinker-Confused: Lists are just wrappers around arrays. It's hard to make something faster by adding indirection, so lists will be very slightly slower.
  • Learning-Overthinker-Confused
    Learning-Overthinker-Confused over 6 years
    @EricLippert First of all thank you so much for replying to my comment.I am trying to compare 2 unordered list by getting data from 2 different rdbms and then doing comparision in memory.which will be more efficient for this:Array or list?
  • Eric Lippert
    Eric Lippert over 6 years
    @Learning-Overthinker-Confused: You have two horses. You wish to know which is faster. Do you (1) race the horses, or (2) ask a stranger on the internet who has never seen the horses which one he thinks is faster? Race your horses. You want to know which one is more "efficient"? First create a measurable standard for efficiency; remember, efficiency is value produced per unit cost, so define your value and cost carefully. Then write the code both ways and measure its efficiency. Use science to answer scientific questions, not asking random strangers for guesses.
  • Learning-Overthinker-Confused
    Learning-Overthinker-Confused over 6 years
    @EricLippert You are right.I am sorry sir.Actually one of my colleague told me that generic array(t[]) are faster than list because generic or pure array are written in low level programming language.hence i am searching for this that it is true or not
  • Eric Lippert
    Eric Lippert over 6 years
    @Learning-Overthinker-Confused: Remember that "faster" is irrelevant. Your customer does not care about "faster". Your customer cares about fast enough. If arrays and lists are so similar that the customer can't tell the difference then it doesn't matter. If arrays and lists are both too slow for the customer's requirements, then which is faster doesn't matter. Always consider performance with respect to customer scenarios. You can waste a lot of time optimizing code in a way that buys no goodwill from the customer.
  • Eric Lippert
    Eric Lippert over 6 years
    @Learning-Overthinker-Confused: But again, if you have a question about which of two things is faster, write a test and see if there is an observable difference. A difference that cannot be observed is a difference that doesn't matter.
  • Learning-Overthinker-Confused
    Learning-Overthinker-Confused over 6 years
    @EricLippert Actually i have 2 different rdbms like mysql and oracle which contains millions of records.I want to fetch this millions of records from relevant Rdbms table and then compare them in memory based on some rules.So i am searching for an efficient algorithm and appropriate data structure for this :)
  • R. Navega
    R. Navega almost 6 years
    How are you supposed to use this structure? Is it like a dictionary?
  • grooveplex
    grooveplex over 5 years
    @R.Navega it's an ordinary array :)
  • Second Person Shooter
    Second Person Shooter over 5 years
    Are the given examples complete? Is there any other case?
  • Ruben9922
    Ruben9922 almost 5 years
    Out of curiosity, could someone explain why the initialisation expression in the 3rd line can't be used by itself (e.g. passed into a method) or be assigned to a var variable?
  • TvdH
    TvdH over 4 years
    @Ruben9922: Interesting question. It would make sense that var x = {} does not work if the array initializer could yield anything else than arrays, but I would not know what that is. So I guess the array initializer is a language feature. If you use it with new List<string> {"A", "B"}it yields something different, too.
  • Lou
    Lou over 3 years
    Is there any reason ever to use string array = new string[] { "A", "B" }; over string array = { "A", "B" };? The first just seems redundant.
  • Lorenzo
    Lorenzo over 3 years
    @Lou The syntax comes from the ability to explicitly specify the type in case it cannot be automatically inferred. But of course, in the case of primitive string types that notation definitely seems redundant
  • Can Sahin
    Can Sahin over 3 years
    @Ruben9922: Interestingly, Dim a = { "A", "B" } does work in VB.NET (with Option Strict On and Option Infer On) and correctly infers String() (string[] in C#) as the data type, so I guess the C# designers made a deliberate choice of not supporting this. I guess it was easier to implement in VB, since VB only uses curly braces for array initializations (as opposed to C#, where you have curly braces everywhere). In VB, you can also write Return {} in a method that returns an array.
  • Suncat2000
    Suncat2000 over 2 years
    @grooveplex It's an array of anonymous types. The anonymous types contain the members Name of type string and PhoneNumbers of type string[]. The types are inferred by the compiler.
  • Frank
    Frank over 2 years
    I tried calling and Mr Yang said Mr Feng moved out in 2018