SomeRandomOnlineDev
Member
- Joined
- Oct 23, 2023
- Messages
- 6
- Programming Experience
- Beginner
I am making a very simple database reader that can create a file with information (first name, last name, age, gender), read a file and decode that information and put it into a class, and delete said files. In a certain part of the program, I have set a class's variables to null to prevent some errors being thrown elsewhere. However, in this class, one of the variables depends on the information of another variable, the first name, adds "_Info.txt" to it and calls it the file name. I have added a try catch statement when this assignment occurs to prevent this exception, however it seems to be happening in the actual get; set; function, and I'm not sure how to fix it.
Here is the class in question (There's slightly more to it than this but it's not relevant):
And here is where I have set an instance of the class to null to prevent errors:
And here is why I have it set to null:
Here is the class in question (There's slightly more to it than this but it's not relevant):
the class the error is occuring in:
class Person {
public Person(string firstName, string lastName, int age, string gender) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
try {
this.fileName = this.firstName.ToLower() + "_Info.txt"; // this is where I thought it was being troublesome
}
catch (System.NullReferenceException) {
this.fileName = "_Info.txt";
}
}
public string firstName { get; set; } // this is where it's throwing the error inside the class
public string lastName { get; set; }
public int age { get; set; }
public string gender { get; set; }
public string fileName { get; set; }
}
And here is where I have set an instance of the class to null to prevent errors:
where i have set it to null:
Person person = new Person(null, null, 0, null);
And here is why I have it set to null:
Why i set it to null:
if (choice != "exit") {
for (int i = 0; i < database.Count; i++) {
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") {
person.createPersonFile(); // this line here was being problematic, so I have the person set to null earlier
}
else if (choice == "2") {
person.deletePersonFile();
}
}