All possible array initialization syntaxes
Asked Answered
C

20

896

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

Cyclopean answered 15/4, 2011 at 14:27 Comment(0)
T
975

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" }; // creates populated array of length 2
string[] array = ["A", "B"]; // creates 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. The fifth line was introduced in C# 12 as collection expressions where the target type cannot be inferenced. It can also be used for spans and lists. 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
string[] array = ["A", "B"]; // creates populated array of length 2
Treble answered 15/4, 2011 at 14:29 Comment(2)
The C#12 Collection expressions can also be used for Lists<> ect. and they are also nice to instantiate an empty Array/List like this: string[] arr = [] or List<string> list = [] Additional LinkEhrenburg
For completeness, string[] array = new string[2] { "A", "B" }; also works. string[] array = new string[3] { "A", "B" }; or string[] array = new string[1] { "A", "B" }; are errors because of length mismatch.Raina
N
474

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".

Nasser answered 15/4, 2011 at 14:41 Comment(8)
What is the new[] { ... } (or new { ... } for other types) syntax known as?Exaggeration
@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".Nasser
Not exactly C# "syntax", but let's not forget (my personal favorite) Array.CreateInstance(typeof(int), 3)!Greylag
@Jeffrey: If we're going down that road,it starts getting silly. E.g., "1,2,3,4".split(',').Rhoda
Then for multi-dimensional arrays, there exist "nested" notations like new int[,] { { 3, 7 }, { 103, 107 }, { 10003, 10007 }, };, and so on for int[,,], int[,,,], ...Tatum
@EricLippert:Is pure array or generic array like abc[] is faster than list because it is written in low level programming language?Empiric
@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?Empiric
@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 notEmpiric
E
133

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
Exosmosis answered 14/8, 2014 at 18:21 Comment(1)
It would be good to more clearly separate the invalid syntaxes from the valid ones.Hydrolyse
W
62
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.

Wachter answered 6/5, 2014 at 9:5 Comment(1)
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.Tatum
C
27
var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};
Coercive answered 29/8, 2015 at 11:31 Comment(3)
How are you supposed to use this structure? Is it like a dictionary?Pennsylvanian
@R.Navega it's an ordinary array :)Beitnes
@Beitnes 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.Catholicism
M
27

In case you want to initialize a fixed array of pre-initialized equal (non-null or other than default) elements, use this:

var array = Enumerable.Repeat(string.Empty, 37).ToArray();

Also please take part in this discussion.

Myosotis answered 20/12, 2015 at 9:33 Comment(0)
E
14

Example to create an array of a custom class

Below is the class definition.

public class DummyUser
{
    public string email { get; set; }
    public string language { get; set; }
}

This is how you can initialize the array:

private DummyUser[] arrDummyUser = new DummyUser[]
{
    new DummyUser{
       email = "[email protected]",
       language = "English"
    },
    new DummyUser{
       email = "[email protected]",
       language = "Spanish"
    }
};
Erdrich answered 2/9, 2016 at 0:9 Comment(0)
H
11

Just a note

The following arrays:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };

Will be compiled to:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };
Harridan answered 27/4, 2020 at 10:30 Comment(0)
M
10

Repeat without LINQ:

float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
Milicent answered 8/3, 2016 at 20:4 Comment(0)
M
6
int[] array = new int[4]; 
array[0] = 10;
array[1] = 20;
array[2] = 30;

or

string[] week = new string[] {"Sunday","Monday","Tuesday"};

or

string[] array = { "Sunday" , "Monday" };

and in multi dimensional array

    Dim i, j As Integer
    Dim strArr(1, 2) As String

    strArr(0, 0) = "First (0,0)"
    strArr(0, 1) = "Second (0,1)"

    strArr(1, 0) = "Third (1,0)"
    strArr(1, 1) = "Fourth (1,1)"
Merat answered 24/7, 2013 at 6:42 Comment(1)
Hi, the last block of examples appear to be Visual Basic, the question asks for c# examples.Oakes
M
4
For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };
Minutia answered 7/3, 2018 at 16:13 Comment(0)
H
2

Another way of creating and initializing an array of objects. This is similar to the example which @Amol has posted above, except this one uses constructors. A dash of polymorphism sprinkled in, I couldn't resist.

IUser[] userArray = new IUser[]
{
    new DummyUser("[email protected]", "Gibberish"),
    new SmartyUser("[email protected]", "Italian", "Engineer")
};

Classes for context:

interface IUser
{
    string EMail { get; }       // immutable, so get only an no set
    string Language { get; }
}

public class DummyUser : IUser
{
    public DummyUser(string email, string language)
    {
        m_email = email;
        m_language = language;
    }

    private string m_email;
    public string EMail
    {
        get { return m_email; }
    }

    private string m_language;
    public string Language
    {
        get { return m_language; }
    }
}

public class SmartyUser : IUser
{
    public SmartyUser(string email, string language, string occupation)
    {
        m_email = email;
        m_language = language;
        m_occupation = occupation;
    }

    private string m_email;
    public string EMail
    {
        get { return m_email; }
    }

    private string m_language;
    public string Language
    {
        get { return m_language; }
    }

    private string m_occupation;
}
Herrenvolk answered 16/2, 2018 at 1:58 Comment(0)
G
2

hi just to add another way: from this page : https://learn.microsoft.com/it-it/dotnet/api/system.linq.enumerable.range?view=netcore-3.1

you can use this form If you want to Generates a sequence of integral numbers within a specified range strat 0 to 9:

using System.Linq
.....
public int[] arrayName = Enumerable.Range(0, 9).ToArray();
Given answered 22/7, 2020 at 6:9 Comment(0)
I
2

In C# 12, you will able to create an array like this : int[] positions = [1, 2, 3];

Really great !

Injudicious answered 8/9, 2023 at 9:0 Comment(0)
S
1

For the class below:

public class Page
{

    private string data;

    public Page()
    {
    }

    public Page(string data)
    {
        this.Data = data;
    }

    public string Data
    {
        get
        {
            return this.data;
        }
        set
        {
            this.data = value;
        }
    }
}

you can initialize the array of above object as below.

Pages = new Page[] { new Page("a string") };

Hope this helps.

Scorekeeper answered 14/1, 2020 at 8:36 Comment(0)
C
0

You can also create dynamic arrays i.e. you can first ask the size of the array from the user before creating it.

Console.Write("Enter size of array");
int n = Convert.ToInt16(Console.ReadLine());

int[] dynamicSizedArray= new int[n]; // Here we have created an array of size n
Console.WriteLine("Input Elements");
for(int i=0;i<n;i++)
{
     dynamicSizedArray[i] = Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine("Elements of array are :");
foreach (int i in dynamicSizedArray)
{
    Console.WriteLine(i);
}
Console.ReadKey();
Camber answered 15/9, 2016 at 12:24 Comment(0)
O
0

Trivial solution with expressions. Note that with NewArrayInit you can create just one-dimensional array.

NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback
Olimpia answered 14/6, 2017 at 21:25 Comment(0)
T
0

To initialize an empty array, it should be Array.Empty<T>() in dotnet 5.0

For string

var items = Array.Empty<string>();

For number

var items = Array.Empty<int>();
Trail answered 2/11, 2021 at 4:33 Comment(0)
H
0

Another way is by calling a static function (for a static object) or any function for instance objects. This can be used for member initialisation.

Now I've not tested all of this so I'll put what I've tested (static member and static function)

Class x {
    private static Option[] options = GetOptionList();
    private static Option[] GetOptionList() {

        return (someSourceOfData).Select(dataitem => new Option()
                 {field=dataitem.value,field2=dataitem.othervalue});
    }
}

What I'd love to know is if there is a way to bypass the function declaration. I know in this example it could be used directly, but assume the function is a little more complex and can't be reduced to a single expression.

I imagine something like the following (but it doesn't work)

Class x {
    private static Option[] options = () => {
        Lots of prep stuff here that means we can not just use the next line
        return (someSourceOfData).Select(dataitem => new Option()
                 {field=dataitem.value,field2=dataitem.othervalue});
    }
}

Basically a way of just declaring the function for the scope of filling the variable. I'd love it if someone can show me how to do that.

Hoi answered 13/6, 2022 at 13:20 Comment(0)
K
0

For multi-dimensional array in C# declaration & assign values.

public class Program
{
    static void Main()
    {
        char[][] charArr = new char[][] { new char[] { 'a', 'b' }, new char[] { 'c', 'd' } };

        int[][] intArr = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
    }

}
Kimble answered 23/11, 2022 at 6:29 Comment(2)
This question is asked more than 11 years ago and it has an accepted answer. Please add some details about the reason you are adding a new answerGreenery
I was trying to create a multi-dimension array and retrieve a specified value like the one below, however when I attempted using the syntax provided by Microsoft in link VS gave me a syntax error. In an effort to aid someone in the future, I posted to this question. int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; Console.WriteLine(array2Da[1][1]); //error => array2Da is not null hereKimble

© 2022 - 2024 — McMap. All rights reserved.