The object of your affection

Hi There
Last task in exercise here want you to initialise hobbies array with length of zero in the constructor to prevent exception when ViewProfile is called and hobbies have not been set.

“If you call ViewProfile() before calling SetHobbies() , you’ll get an error because the hobbies field isn’t set to any value. Fix the class so that you can call ViewProfile() without adding hobbies.”

In the constructor of ViewProfile, I’ve tried to initialise hobbies array with length of zero with no luck, can anyone help with what I doing incorrectly?

As is is below I get an error saying that value for hobbies must be a compile time constant.
How does one initialise array with length of 0 in ViewProfile constructor?

namespace DatingProfile
class Profile
private string name;
private int age;
private string city;
private string country;
private string pronouns;
private string hobbies;

public Profile(string name,int age,string city,string country,string pronouns = "they/them",string[] hobbies = new string[0])

{ = name;
this.age = age; = city; = country;
this.pronouns = pronouns;
this.hobbies = hobbies;

You can intialize the hobbies string array to an empty array like so:

private string[] hobbies = new string[] {};

Also, for future posts, please use the </> button to format your code. Go to a new line, then click the </> button in the menu bar, then paste your code in the space indicated. Your code will be preserved the way you originally typed it. Charactes like [] won’t show up like this: . Happy coding!


Thanks midlinder - so to set a default of 0 for the array I do so on the class field member and not inside the profile constructor.
Now this makes sense that I don’t include the hobbies array in the constructor because I already have a method that sets this.
The default at the member level is primarily to stop any errors from arising from calling the ViewProfile method when SetHobbies has not been called.
Thanks again, think I’ve got the gist of this now.

1 Like

You’re welcome! You’ve summed it up perfectly.

EDIT: I just looked back at the project again. The hint says to assign the empty array in the constructor. You can do it the same way:

this.hobbies = new string[]{};

You still would not include hobbies in the parameters for the constructor since hobbies has its own setter method.