0

If I have a constructor with an array like:

public Courses(string courseName, string courseCode, string passingGrade, string numOfCredits, string[] prerequisites)

The array prerequisites is supposed to take whatever prerequisite that a course has, which may be more than one, if I create an object in my main class, how do I add multiple values to it?

Courses courses = new Courses(Computer Science, CS50, C+, 3, this is the array prerequisites, how could I add multiple strings here? )
NewDev
  • 27
  • 7
  • Duplicate of [All possible array initialization syntaxes](https://stackoverflow.com/questions/5678216/all-possible-array-initialization-syntaxes) and/or [Creating methods with infinite parameters?](https://stackoverflow.com/q/2435757/8967612) – 41686d6564 stands w. Palestine Oct 11 '22 at 17:32

2 Answers2

2

You could use the params keyword in your constructor signature like so:

public Courses(string courseName, string courseCode, string passingGrade, string numOfCredits, params string[] prerequisites)

More on the params keyword here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

Note that the example of your constructor call is malformed. It should look like this to use strings:

Courses courses = new Courses("Computer Science", "CS50", "C+", "3", "this is the array prerequisites", "how could I add multiple strings here?");
Luke
  • 743
  • 6
  • 20
2

I think there are two ways of doing this. Firstly you can use the constructor you just defined

public Courses(string courseName, string courseCode, string passingGrade, string numOfCredits, string[] prerequisites)

And when passing the arguments just pass an array as the argument.

var course = new Courses("Abc", "157", "100", "4", new string[] {"ABC", "def ", "abcdef"});

or you can use the params keyword to have the array as comma separated strings.

public Courses(string courseName, string courseCode, string passingGrade, string numOfCredits, params string[] prerequisites)

Which you can call like

var course = new Courses("Abc", "157", "100", "4", "ABC", "def", "abcdef");