Error when using local variable

Joined
Oct 23, 2023
Messages
6
Programming Experience
Beginner
I am creating a database program that can create a file containing information about a person, read that information and convert it into a class called "Person" and also delete said file. The following code is from the function used to view the database and perform action on a given person. The error is happen on "person.createPersonFile();" it says that it using a local unassigned variable how ever in the code, it is clearly assigned. I have no hecking clue what the problem is. Any help? (Also given that I am terrible at explaining things, I'm sorry if this is unclear)
The code in question:
if (choice != "exit") {
    for (int i = 0; i < database.Count; i++) { // convert the name of a person into an actual person object
        if (database[i].firstName == choice) {
            person = database[i];
        }
    }

    Console.Clear();

    Console.Write("ACTION LIST\n\t1. Create a file for this person\n\t2. Delete the file for this person\nEnter your choice with the corresponding number");
    choice = Console.ReadLine();

    if (choice == "1") { // i'm using numbers in quotes because of the way i used the choice variable earlier in the program
        person.createPersonFile(); // this is the line that gives me an error
    }
    else if (choice == "2") {
        person.deletePersonFile();
    }
}
// help please
 
It is only assigned if database.firstName == choice.
 
I suspect what's happening here is that you know that database[i].firstName == choice will be true on one iteration of the loop but that would depend on the data. The code itself cannot guarantee that will ever be true so it cannot guarantee that the variable will be assigned. To avoid compilation errors or warnings, initialise the variable to null before the loop. If you're using a recent version of C#, you should also tell the compiler that the value will definitely not be null at that point:
C#:
person!.createPersonFile();
 
I suspect what's happening here is that you know that database[i].firstName == choice will be true on one iteration of the loop but that would depend on the data. The code itself cannot guarantee that will ever be true so it cannot guarantee that the variable will be assigned. To avoid compilation errors or warnings, initialise the variable to null before the loop. If you're using a recent version of C#, you should also tell the compiler that the value will definitely not be null at that point:
C#:
person!.createPersonFile();

How would I initialize the variable to null? Still a bit new.
 

Latest posts

Back
Top Bottom