-2

I understand how arrays in C# work and that the syntax for their creation is just the tape and square parentheses (e.g. new int[]), optionally followed by special braces with the items that the new array is to be filled with.

The array is, however, internally a (ok, probably not so) normal class. And as one it surely has an implicit constructor (not necessarily) which should be invoked when an array is created which should be reflected by the syntax -> creation should be new int[]() instead of what it is...

But it obviously isn't like that and my question is why... what led them to do that this (unintuitive) way...

Petrroll
  • 741
  • 7
  • 29
  • 2
    What you''re talking about is syntactical sugar provided by C#. `System.Array` is abstract. – Jamiec Mar 10 '15 at 12:24
  • 1
    Why should it? Why do you consider `new int[]()` intuitive? Not to mention that arrays are immutable so this syntax would only create an empty array. `new int[]` is used in C, C++, Java - it's actually the most popular syntax – Panagiotis Kanavos Mar 10 '15 at 12:25
  • Ok, but there still has to be some class that inherits from System.Array, has a constructor, and corresponds to int[]... – Petrroll Mar 10 '15 at 12:26
  • "what led them to do that this (unintuitive) way" - ask them. We can only speculate. (I think @PanagiotisKanavos is correct but to be sure we need Anders or one of his colleagues to enter the discussion) – Emond Mar 10 '15 at 12:26
  • If they had generics when the framework was created perhaps the syntax would have been `new Array()`. – Magnus Mar 10 '15 at 12:30
  • @Petrroll from the [docs](https://msdn.microsoft.com/en-us/library/system.array.aspx) `However, only the system and compilers can derive explicitly from the Array class. Users should employ the array constructs provided by the language.`. – Panagiotis Kanavos Mar 10 '15 at 12:31
  • Ok, I see. I just thought that someone with more insight into how the language works could explain to me why they did it that way... Anyway, I've managed to find what I was looking for here (basically that arrays are not exactly and just normal objects but are special): http://stackoverflow.com/questions/4489661/whats-the-magic-of-arrays-in-c-sharp – Petrroll Mar 10 '15 at 12:37

1 Answers1

1

An array is very different form a simple class or other data structures. With an array the memory allocation and access of items is done directly by the CLR and/or the compiler. With other data structures this is handeled by the data-structure code.

So for allocating an array of a certain size some syntax is needed which let the compiler do the job. var arr = new int[5]

instead of a syntax which calls a data-structure's constructor like var list = new List<int>(5)

DrKoch
  • 9,556
  • 2
  • 34
  • 43