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