-3

I've seen All possible C# array initialization syntaxes which shows several different ways to initialize an array.

Does the following initialization creates an instance that is different in some ways compared to one created with regular call with new ?

Initialization:

string[] strArray = {"one","two","three"}; 

Compared to string[] strArray = new String[] {"one","two","three"};

Community
  • 1
  • 1
cliang86
  • 31
  • 4
  • 2
    have you tried it? What did you get? – Gilad Green Aug 05 '16 at 16:08
  • 1
    What do you mean does it create instance? Did you try it and get an object that you can use? – itsme86 Aug 05 '16 at 16:09
  • @Alexei Levenkov: That's very brave of you, but now you've gone and made the very first sentence of my answer sound strange in hindsight :( – BoltClock Aug 05 '16 at 16:42
  • @BoltClock I've tried to make question sensible (and not duplicate) and keep both your and user3185569 answers valid. I see that I've lost "is it even initilized" spirit that is covered by part of your question - not really sure if I can come up with sane way of asking that part so :). I've closed it as duplicate first, but careful reading showed that this particular aspect is actually not covered in the "All possible C# array initialization syntaxes". – Alexei Levenkov Aug 05 '16 at 16:52
  • @Alexei Levenkov: Yeah, that's OK. It's still a good edit all around :) – BoltClock Aug 05 '16 at 16:55

2 Answers2

1

It is a syntactic sugar. The compiler transforms this:

string[] strArray = {"one","two","three"};

To This:

string[] expr_07 = new string[] {
            "one",
            "two",
            "three"
        };

Above output is using Roslyn C# compiler.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
1

You can't initialize something that's not there. So yes, a new instance does get created, in the exact same way as though you had written the new operator. It's just a convenience provided by the language for when you're initializing an array at the same time that you're declaring it so you aren't forced to write it out (when doing it in a separate statement, the new operator is required because the compiler can't assume you haven't already assigned an array reference to the variable beforehand — the very bare minimum you can get away with in a separate statement is strArray = new[] {...};).

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356