+ 5

Why does an array not behave as a class?

I have learned that an array is a built-in class. Since arrays are objects, we need to instantiate them with the new keyword. *1. But why dont u have to right it actually in a class? *2. Why can I use an array without the ‘new‘ operator? 3. Will it go on the heap or the stack? namespace SoloLearn { class Program { //<———*1. ? static void Main(string[] args) { int[ ] a = new int[5]; int[ ] b = {11, 45, 62, 70, 88}; //<———*2. new? Console.WriteLine(b[2]); Console.WriteLine(b[3]); } } }

14th Dec 2018, 9:58 AM
Mike Willems
Mike Willems - avatar
7 ответов
+ 1
Array cannot behave as class because array is a collection of similar data types But class is a collection of multiple data types... Moreover class provides many functionalities like inheritance, polymorphism etc....
20th Dec 2018, 9:21 AM
Rohit
Rohit - avatar
+ 8
John Wells Indeed. 😎 The Array class itself is an abstract base class used only by the System libraries and compiler to implement language specifications. Developers shouldn't typically work directly with this base class (System.Array) for normal application development. The missing syntax you are referring to is due to the System.Array type not implementing any indexer interfaces. I've created this code to demonstrate this point by comparing the interfaces implemented by the System.Array and int[] types. You'll notice that the int[] type implements 5 different indexer interfaces where System.Array implemented no indexer interfaces. https://code.sololearn.com/c5b93iIiMJ3h/?ref=app
15th Dec 2018, 5:54 AM
David Carroll
David Carroll - avatar
+ 5
1. I don't understand your first question. Can you rephrase it? 2. int[] b = { 11, 45, 62, 70, 88 } is actually syntactic sugar that is rewritten in IL as if the code was written in C# as: int[] b = new int[5]; int[0] = 11; int[1] = 45; int[2] = 62; int[3] = 70; int[4] = 88; 3. Arrays are stored on the heap. However, they can be stored on the stack using the stackalloc keyword in an unsafe context.
15th Dec 2018, 4:03 AM
David Carroll
David Carroll - avatar
+ 4
Added C# tag to thread. C# is based on C where arrays are not classes so as a compromise the compiler handles it for you so existing C code could still run as C#. It is as if you used the Array class and should be considered heap, but that is a compiler implementation dependency.
14th Dec 2018, 11:39 PM
John Wells
John Wells - avatar
+ 4
Something I just learned: you can't mix int[] array syntax with Array syntax. The following is purely Array syntax implementation. https://code.sololearn.com/cNbfsf0KSN4E
15th Dec 2018, 4:32 AM
John Wells
John Wells - avatar
+ 2
@Rohit... In C#, System.Array is an abstract class. See earlier answers posted in this thread.
21st Dec 2018, 3:00 AM
David Carroll
David Carroll - avatar
+ 1
thank you for your explanation and time.
15th Dec 2018, 8:58 PM
Mike Willems
Mike Willems - avatar