tags:

views:

943

answers:

6

How do you initialize an array in C#?

+14  A: 

Like this:

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

or this:

int[] values = new int[3];
values[0] = 1;
values[1] = 2;
values[2] = 3;
Andrew Hare
Strictly speaking the second method is not called initialization. Thought that the reader was interested in initializers.
Charles Prakash Dasari
A: 
char[] charArray = new char[10];

If you're using C# 3.0 or above and you're initializing values in the decleration, you can omit the type (because it's inferred)

var charArray2 = new [] {'a', 'b', 'c'};
Andreas Grech
+11  A: 
var array = new[] { item1, item2 }; // C# 3.0 and above.
Mehrdad Afshari
+1 This is good to mention too.
Andrew Hare
Downvoter: care to explain?
Mehrdad Afshari
+2  A: 
int [ ] newArray = new int [ ] { 1 , 2 , 3 } ;
A: 
string[] array = new string[] { "a", "b", "c" };
Dan
+4  A: 

Read this

http://msdn.microsoft.com/en-us/library/aa288453%28VS.71%29.aspx

//can be any length
            int[] example1 = new int[]{ 1, 2, 3 };

            //must have length of two
            int[] example2 = new int[2]{1, 2};           

            //multi-dimensional variable length
            int[,] example3 = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 } };


            //multi-dimensional fixed length
            int[,] example4 = new int[1,2] { { 1, 2} };

            //array of array (jagged)
            int[][] example5 = new int[5][];
Steve