Tech Off Post

Single Post Permalink

View Thread: C# array constructor & initialization
  • User profile image
    amotif

    janzenr wrote:
    I am under the impression that:

    new String[] { "foo", "bar"};

    and

    new String();

    are just constructors.   new String(); does not new up to anything, unlike the behavior of the array, right? 


        new String[] { "foo", "bar"};

    allocates and array and assigns elements

        new String();

    would allocate a String instance, if it actually compiled. It won't compile because there is no default ctor for String (String is immutable, so it wouldn't make much sense).

        new Object();

    This compiles and creates a new instance of Object. Your "does not new up to anything" statement isn't correct, as far as I understand your words.

    janzenr wrote:
    Also if I pass new String[] { "Foo", "bar"} as a function's parameter, it compiles. Ex:

    Console.WriteLine(new String[] { "foo", "bar" });

    We still have a problem here.


    I don't see the problem. Your example of passing the initialized array as a parameter is a completely different context than your original question, which tries to use the initialized array as a statement unto itself. And *that* is the subject of the error message you get.

    As to "why," I'd guess that has something to do with the language spec.