0

I just started to learn C# and I came across the fact that Array is an abstract class, not a concrete one. I am wondering how it is possible that array instances can be created if it is declared as abstract in the documentation (as seen in https://learn.microsoft.com/en-us/dotnet/api/system.array?view=net-5.0).

Bernard Borg
  • 1,225
  • 1
  • 5
  • 18
  • you can not directly instantiate the `Array` class, if you looking for a way to instantiate an array read [this](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/) – Patrick Beynio Dec 05 '20 at 20:59
  • 1
    As per remarks on the linked article, the compiler is allowed to derive from it, and only the system and the compiler. It's a special class. – Mephy Dec 05 '20 at 21:03
  • See https://stackoverflow.com/questions/19914523/mystery-behind-system-array#comment29631862_19914523 and https://stackoverflow.com/questions/11163297/how-do-arrays-in-c-sharp-partially-implement-ilistt/11164210#11164210 and note that they are speaking of single-dimensional-zero-based arrays (the normal arrays). In .NET there are multidimensional arrays `int[1, 2]` and non-zero based arrays (array for example that have the first index at 1). Those are based on a different sleight of hand. "Standard" arrays are supported by `SZArrayHelper` (Single dimension, Zero based) – xanatos Dec 05 '20 at 22:06
  • _"how it is possible that array instances can be created"_ -- how is it possible that `TextWriter` and `TextReader` instances can be created? How is it possible that `Stream` instances can be created? How is possible that _any_ `abstract` class can be created? Frankly, this question doesn't make sense...you are either asking how something can be done that is obvious (i.e. you create **subclasses** of `Array`, not `Array` itself), or you are asking how something that _can't_ be done can be done (i.e. create bare instances of `Array`). Either way, not useful. – Peter Duniho May 29 '21 at 21:23

1 Answers1

2

'Array' is an abstract class, so it cannot be instantiated directly. However it has an static 'CreateInstance' method, which creates an instance of a concrete implementation of an array containing elements of the required type.
see https://learn.microsoft.com/en-us/dotnet/api/system.array.createinstance?view=net-5.0#System_Array_CreateInstance_System_Type_System_Int32_

and also: Difference between Array.CreateInstance and using the new operator to create new array instance

Johan Donne
  • 3,104
  • 14
  • 21