Object of Your Desire step 12


Having an issue with step 12, checking to see if hobbies array is greater than 0 in an if statement:

 public string ViewProfile()
        {   string profileInfo = 
            $"{name}. From {city}, {country}. Is {age} years old. {pronouns}.";
          if (hobbies.Length > 0)
            profileInfo = profileInfo + " Likes: ";
            foreach (string hobby in hobbies)
              profileInfo = profileInfo + hobby + ", ";
          return profileInfo;

I can comment out the if statement and it works. The error I’m getting is “unhandled exception object reference not set to an instance of an object”. I read up on it and it said the error may occur if the data is set to null. In the constructor, I have

string[] hobbies = new string[0];

Again, this works, so long as I don’t have an if statement. I’ve tried referencing the length of hobbies with the this keyword, and I get the same error.

Hi there, welcome to the forums!

I’m guessing that your issue is that hobbies is not defined in that scope…

Do you have a hobbies variable declared elsewhere? I think you probably do. In which case, are you sure you’re referencing it correctly?

Hint: You’re working inside a class… what’s the correct way to reference a class attribute from inside the object created by the class?

I had it declared as a field and in the constructor with and without this keyword and set it to length [0] in the constructor both ways, but I didn’t have it as a parameter. I didn’t think to try it as a parameter.
The text of the project gives the idea that you have to set the length to [0] and then run an if statement to see the length. I think the problem was unless the values are actually set within the array, it didn’t like trying to figure out if the length of null was greater than 0.

What I ended up doing is just added a field for the profile string, handed the string over to the constructor so that a “profile” was built for each Profile object, and handed the foreach loop to SetHobbies(). The field could then be called from ViewProfile(). This solution makes setting hobbies optional and just adds them onto the string when and only when SetHobbies() is called.

Hi, I think

is wrong in the constructor. This way you initialise a new string.

I managed to run the code by setting the existing field

private string hobbies;


hobbies = new string[0];

in the constructor. This way I set the field to an empty array.

Then in the SetHobbies() method i set the field hobbies to the array I initialise with the method:

this.hobbies = hobbies

and in the ViewProfile() method I check if this array is longer than 0:

if (this.hobbies.Length > 0)

Here is my entire code for the Profile class:

It works, but I am not very confident how “this” works…