+ 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]); } } }
7 Antworten
+ 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....
+ 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
+ 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.
+ 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.
+ 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
+ 2
@Rohit... In C#, System.Array is an abstract class. See earlier answers posted in this thread.
+ 1
thank you for your explanation and time.