What is the difference in the ways of declaring an array?

I was wondering while researching arrays in the C# Microsoft reference if there’s any difference (and there must be, its computer science after all) between declaring the array in Ben’s way and declaring it this way;

Ben’s way:

String[] level1Passwords = { "book", "pencil", "pen" };

other way:

int[] scores = new int[] { 97, 92, 81, 60 };

What is the use of this “new int []” before listing the array’s objects?
Wasn’t it enough to write down the “int[]” before the name of the array?

Thank you for your time and convenience~

Reference:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/

1 Like

Hi,

If you are both declaring and initialising the array at the same time, you don’t need to specify the new keyword.

So, for example;

string[] level1Passwords = { "book", "pencil", "pen" };

and;

int[] scores = { 97, 92, 81, 60 };

are both acceptable as short-cuts.

Differences arise however when you declare the array without initialising it at the same time, in which case, when you initialise the variable, you need to use the new keyword;

int[] scores;
scores = new int[] { 1, 3, 5, 7, 8 };

string[] level1Passwords;
level1Passwords = new string[] { "book", "pencil", "pen" };

There are some examples on the page I have linked below for you.

Hope this helps :slight_smile:


See also;

2 Likes

I see.
Genius Rob to the rescue.
Can’t thank you enough.

1 Like

Hi Omar,

You’re very welcome, happy to help.

Incidentally, it was a great question and the fact you noticed the difference is a credit to you, its often these subtle differences that trip us up when writing code, so we’ll done :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms