Question Arrays

Bryan_James

Member
Joined
Jul 6, 2016
Messages
5
Location
Philippines
Programming Experience
1-3
Hi!
I'm new to C#. I have concerns regarding arrays.
[1]
C#:
int[] int_arr = {1, 2, 3, 4, 5};
[2]
C#:
int[] int_arr = new int[]{1, 2, 3, 4, 5};
I searched MSDN and other sites about this. They said that arrays in C# are objects, which is, System.Array is the abstract base type of all arrays. I understand that in [2], the int is being instantiated then initialized. Meanwhile, [1] didn't instantiate the integer type array. What is the major difference between the two? Why and when should I use [1] instead of [2] and vice versa? Why does [1] works without instantiating it?

Thanks in advance!
 
Those two lines of code are functionally equivalent. There is no specific situation where you should use one over the other. You should choose which one you prefer to use and stick with it. The second line specifies on the right of the assignment that the object is an int array while the first line infers it. Type inference is required in certain situations and it was introduced to support LINQ but it makes your code more concise in many situations, including this one. In the first line, the compiler knows that what's on the right is an array because of the braces and it can see that each element is an int so it infers that it is an int array without your having to specify that explicitly as you do in the second line.
 
Back
Top Bottom