Question

Without initialization how is it possible to assign values to arrays?

string[] s={"all","in","all"};

I mean why did not the compile show error?.Normally we need to 
initialize ,before assign values.
Was it helpful?

Solution

It's just syntactic sugar.

This:

string[] s = {"all","in","all"};

is compiled to the same code as:

string[] tmp = new string[3];
tmp[0] = "all";
tmp[1] = "in";
tmp[2] = "all";
string[] s = tmp;

Note that the array reference is not assigned to s until all the elements have been assigned. That isn't important in this particular case where we're declaring a new variable, but it would make a different in this situation:

string[] s = { "first", "second" };
s = new string[] { s[1], s[0] };

The same is true for object and collection initializers - the variable is only assigned at the end.

OTHER TIPS

It is possible to declare an array variable without initialization.

Check this out http://msdn.microsoft.com/en-us/library/0a7fscd0%28VS.71%29.aspx

You aren't "assigning a value to array". You are initializing a variable of type "reference to array". The value with which you initialize it is a reference to an array which was created by the use of short array initializer syntax {...}. While it is only permissible in initializer of variables of array type, it is exactly equivalent to new T[] { ... }, where T is deduced from type of variable.

I think you want to know why

 string[] s={"all","in","all"};

works when you would expect to be required to initialize the array first like this :

string[] s = new string[];

or

string[] s = new string[] {"all","in","all"};

The answer is just compiler magic. The compiler knows based on the initialization how big to make the array so it just does it behind the scenes for you. Much like the var keyword, the point is to limit the amount of redundant information you're required to type.

The {"all","in","all"} part is the initialization. the new string[] part can be omitted because the curly braces and string are short hand notation. Take a look at MSDN on Single Dimension Arrays.

string[] s = new string[] { "all","in","all"};

and its shorthand version

string[] s = {"all","in","all"};

are the same thing. See MSDN (Initializing Arrays section) for more detail.

You don't need the new string[] part in C#3 or higher - this works fine

string[] s = { "all","in","all"};

It's just a case of the compiler being a bit smarter and working out what you mean - the back end IL will be the same.

You can do so simply because it is allowed, doing so in two steps is not necessary so this is the shorthand. Consider it sugar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top