0

When initialising new arrays in C#, you can use either

int[] array1 = new int[] { 1, 3, 5, 7, 9 };

or

int[] array1 = { 1, 3, 5, 7, 9 };

Is there a use case in which you should use the new int[] version when instantiating an array instead of the shorthand variant?

Liam Pillay
  • 592
  • 1
  • 4
  • 19
  • 1
    When using var: `var array1 = new int[] { 1, 3, 5, 7, 9 };` – Tieson T. Nov 01 '20 at 06:53
  • 3
    Note that this is initializing (an array), which is not the same thing as instantiating. `new` instantiates, initializing gives initial values (instantiation is an implicit precursory step) – Caius Jard Nov 01 '20 at 07:04
  • Also see this https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/single-dimensional-arrays – TheGeneral Nov 01 '20 at 09:56

1 Answers1

1

Yes, This is mostly used when you are only declaring the array. For Example you want to take values from user, than you will just declare the array. You will declare the size of the array in the bracket as shown below. In this example, "6" is the size of array.

int[] array1 = new int [6]

Now Let's takes the value from user and stored it in the array.

for(int i = 0 ; i < array1.length ; i++)
{
array1[i] = int.parse(Console.ReadLine()); 
}

Now, In above Example, you can see that we have run the for loop till length of array. that is 6. array1.length is the property of array that returns the length of the array. int.Parse((Console.ReadLine()) will take the input of the user that will stored it in the ith index of the array.

In short, you can say that we use "new" keyword when we just have to declare the array and don't have to initialize the values. I hope, it will help you.