When to use the "new" keyword in C#

Hello everyone!

My question is about this project. (The “True or False” project within the Arrays & Loops module of the C# course.)

I’m sure this is a very basic question, so apologies in advance! But other forums (non-Codecademy) I’ve looked at that answer this question go way too far into detail for me to understand.

In this project, we are supposed to create an array of questions to ask the user, who will then answer each with “true” or “false.” I declared my array thus:

string[] questions = {"3 is equal to 5", "A horse is not a primate", "Van Gogh lived in the 21st century"};

But in the accompanying tutorial video, the Codecademy programmer includes “new string” on the right side of the equals sign, before the first opening bracket. Running my code, it still works fine. What is the rule for using the “new” keyword vs not using it, especially if I didn’t run into issues this time around?

Thanks much! :slight_smile:
-Justin

I’ll ignore all the use cases of new and focus on when to use new when creating a new array.
When creating an array we can do it a number of ways:

var stringArraySize = new string[10]; // this will create a new array with 10 items, all set to the default value of the string type (null)

var stringArraySizeInit = new string[10] {"1", "2", "3"}; // this will create a new string array of size 10, with the initial values set to those between {}, if there are less than 10 items initialised the rest will be the default value.

string[] stringArrayInit = {"1", "2", "3"}; // this will create a new array that will be initialised with the values between {} and will have a length equal to the number of values, i.e. 3 in this case.

var stringArrayInitNew = new string[] {"1", "2", "3"}; // verbose version of stringArrayInit

In all the above cases to can replace var with string[] but you cannot swap string[] for var in stringArrayInit. stringArrayInit is just a nice shorthand for stringArrayInitNew, it will compile down to the same thing.

So they have slightly different use cases and only in one case do you not need to use new explicitly, but you can still write it verbosely with new. In the newer versions of C#, you will see a few more cases where they have given shorthand syntax to remove some of the boilerplate code, but it still means the same as the long hand, it just cleans the code up a bit.

That helps. Thanks jagking! :slight_smile:
-Justin