1

In C#, the array can be initialized by the following syntax

string[]arr = {"text1","text2"}; // this works

why does the following not work

string[]arr1;
arr1={"phrase1","phrase2"};//Does not compile. 
AlwaysAProgrammer
  • 2,927
  • 2
  • 31
  • 40

3 Answers3

8
string[] arr = { "text1", "text2" };

This works because this is a special syntax only allowed when first initializing an array variable (personally I didn't even know it existed).

If you want to later assign a new array to a variable, you need to say new:

arr = new string[] { "text1", "text2" };

You can also say just new [] and the compiler will figure out the type for you.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • In your first example Resharper would mark the `new string[]` as unnecessary (if you had included it), because of this shorthand notation. – Jonathon Reinhart Oct 09 '13 at 00:28
3

The second syntax is wrong according to the C# specification: http://msdn.microsoft.com/en-us/library/aa664573%28v=vs.71%29.aspx

Check that link as well for more examples about how to initialize an array: All possible C# array initialization syntaxes

Community
  • 1
  • 1
Rami
  • 7,162
  • 1
  • 22
  • 19
  • +0: while links looks reasonable you should inline summary of external links in the post. I.e. in this case one or two sentences quotes from the specification would make answer much better. Local (SO) links is more ok, but it is still good practice to provide summary + link rather than just link (i.e. if other post deleted most people will not be able to see it). – Alexei Levenkov Oct 09 '13 at 01:04
0

It's all about allocating memory. The first is short for:

string[]arr = new string[]{"text1","text2"};

So the compiler knows in the same statement the number of elements to allocate using the new keyword.

The second is just wrong syntax. If you want to do it in two steps:

string[]arr1; // defines array(pointer)
arr1=new string[]{"phrase1","phrase2"}; // again when `new` is used for dynamic memory allocation, the size is available.
Jerry
  • 4,258
  • 3
  • 31
  • 58