When someone writes:
string[] ArrayofStrings = new string[3]
What is really going on behind the scenes? Like the foreach being syntactic sugar for moving an ienunerator, is this similiar?
When someone writes:
string[] ArrayofStrings = new string[3]
What is really going on behind the scenes? Like the foreach being syntactic sugar for moving an ienunerator, is this similiar?
Yes, there is some syntactic sugar in:
string[] ArrayofStrings = new string[3]
First, there is the C# alias string
for the Base Class Library type System.String
. [I hate it.]
Second, array constructors don't look like other constructors. Without a special syntax, you have to write:
string[] ArrayofStrings2 = (string[])Array.CreateInstance(typeof(string), 3);
As you can easily see in LINQPad or ildasm, these two statements don't emit the same IL. The first way calls
newarr System.String
where as the second does that through
call System.Array.CreateInstance
castclass System.String[]
(I figure if the C# language didn't have that syntactic-sugar, the C# compiler would do some compiler magic and emit the first IL rather than the second.)
But, as @mjwills points out, other initializer expressions might be more complete in that it is doubtful that you want an array of nulls.
I might get you wrong so feel free to ask for clarification.
A string is an array of characters itself, so basically you have an array of arrays.
Now, arrays themselves are collections, where you provide a reference to the first element (marked with 0) and how many more elements are after the first. In your case you have 3 (starting from 0 to 2). You can index them by telling the difference to the first element as those elements are right next to each other on in the memory.
So you have an array of chars, meaning the string
and that is an element of ArrayOfStrings
, which itself is also an array.
string[] ArrayofStrings = new string[3]
just means:
I would like a variable, called ArrayofStrings - and I would like for it to have three elements, all of which are null strings.
It isn't really syntactic sugar, in the way that ?. is, for example.
For some other approaches to initialising arrays, give https://stackoverflow.com/a/5678244/34092 a read.