Where do the Array gets initialized if we do not pass the size of the array explicitly?

74 Views Asked by At

I am new to programming. While learning the data structure Array, I came to know that we have to initialize the array with the size, while creating one. But I also saw a code snippet in one of the sites which i make use to learn coding. The code is as follows

int[] ar = Array.ConvertAll(Console.ReadLine().Split(' '), arTemp => Convert.ToInt32(arTemp))

I guess the code is to read the input from the console(which is a string) and splits it into substrings and then convert into integer array and gets stored in 'ar'.

My question is that there were no errors on this line. But the array size is not mentioned before using them. How is that? where do the size of this array gets initialized in this case?

2

There are 2 best solutions below

0
Prasad Telkikar On BEST ANSWER

From MSDN:

Array.ConvertAll(): Converts an array of one type to an array of another type.


where do the size of this array gets initialized in this case?

In Array.ConvertAll() static function, Size array is based on your input array.

In your case input array is Console.ReadLine().Split(' '). Split(' ')returns an array of space seperated words. Size of this array get assigned to the output of Array.ConvertAll() function

int[] ar = Array.ConvertAll(Console.ReadLine().Split(' '), arTemp => Convert.ToInt32(arTemp))
    //+      +++++++++++++   ++++++++++++++++++++++++                   ++++++
    //|             |                     |                                |
    //|             |                     |                                + Integer convertor
    //|             |                     |
    //|             |                     +   Input array with it's size
    //|             |
    //|             + Converting input array to array of type int
    //|
    //+ Output integer array
0
sillo01 On

int ar is a reference to an array. The array size is determined at runtime. Array.ConvertAll(...) returns an array, the actual object. This new array created is linked to the ar variable.