1

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?

  • 1
    Did you post all the code you wanted to show? That just initializes a new array with three items, there is no "foreach" or anything. – Karl-Johan Sjögren Jul 16 '17 at 14:02
  • I guess, he just asked is there some "magic behind the scenes". But there's no magic, it's simply creating Array of string that size is 3. In such cases you can just decompile code and look at the interpreted language implementation. – Givi Jul 16 '17 at 14:04
  • 3
    That is not sugar for anything, its not expanded to other code when compiled, infact the single `newarr` IL instruction is responsible for creating it. – Alex K. Jul 16 '17 at 14:08
  • In what sense do you mean this is syntactic sugar? – Martin Smith Jul 16 '17 at 14:14

3 Answers3

2

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.

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72
0

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.

agiro
  • 2,018
  • 2
  • 30
  • 62
0
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.

mjwills
  • 23,389
  • 6
  • 40
  • 63