Having problem with The Object of your affection exercise

I keep getting Error CS0165: Use of unassigned local variable ‘hobby’. I have the variable assigned in the method but I can’t figure out why this is happening. Here is my code:

Program.cs

sing System; namespace DatingProfile { class Program { static void Main(string[] args) { Profile sam = new Profile(name: "Sam Drakkila", age: 30, city: "New York", country: "USA", pronouns: "he/him"); string[] h = {"stuff", "things", "whatnot"}; sam.SetHobbies(h); Console.WriteLine(sam.ViewProfile()); } } }

Profile.cs
The error happens in this file on line 32

using System; namespace DatingProfile { class Profile{ // Fields private string name; private int age; private string city; private string country; private string pronouns; private string[] hobbies; // Constructors public Profile(string name, int age, string city, string country, string pronouns = "they/them") { this.name = name; this.age = age; this.city = city; this.country = country; this.pronouns = pronouns; this.hobbies = new string[0]; } // public methods public string ViewProfile(){ string hobby; foreach (string i in this.hobbies){ hobby += $"o {i}\n"; } string info = $"{this.name} is {this.age} and lives in {this.city}, {this.country}. {this.name}'s pronouns are {this.pronouns}.\nThere hobbies are:\n{hobby}"; return info; } public void SetHobbies(string[] hobbies){ this.hobbies = hobbies; } } }
hobby += $"o {i}\n";

is shorthand for

hobby = hobby + $"o {i}\n";

but when you declared the variable on line 30, you didn’t assign any value to hobby
If you change

string hobby;

to the empty string, it should work.

string hobby = "";
1 Like

That fixed it. Thank you I know it was going to be something small lol.

1 Like