I keep getting error CS0165

The exercise is The-Object-of-Your-Affection. When I try to loop through the array hobbies to format it the way I want I get the error CS0165: Use of unassigned local variable ‘hobby’. Here is the code I have so far:


using 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()); } } }

The error is in this file. The method starts on line 29.

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; } } }

Since hobby is not uninitialized and you are attempting to add values onto it, thus the compiler generates this error.

This avoids the necessity of overly complex rules for definite assignment.

This is mostly (I cant be 100% sure) because hobby is null when you don’t assign value to it. Adding value on it has a large possibility to cause unexpected error.