So, I’m building this program in C# in which you can enter membership details, confirm them, and view previously stored memberships. I am still very much a beginner and this is just some school homework.
My teacher suggested to write and read membership details to a file but I had no idea how to do this efficiently so just added them all to a list. I wrote this part to retrieve the username, password and membership type. However, how do i stop an ‘unhandled’ error if the user enters a value in which doesn’t have any stored data?
Here is the code: the list is called membersList.
Console.WriteLine("Which stored membership would you like to view? (e.g 1, 2..)");
int membChoice = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Membership Entry " + membChoice);
Console.WriteLine("Username: " + membersList[membChoice*3-3]);
Console.WriteLine("Password: " + membersList[membChoice*3-2]);
Console.WriteLine("Membership Type: " + membersList[membChoice*3-1].ToUpper());
This results in an unhandled expection error if you enter a larger value than members already stored.
>Solution :
You will first need to check if the list has an element at the position you want:
if(list.ElementAtOrDefault(membChoice*3-3]) != null)
{
Console.WriteLine("Username: " + membersList[membChoice*3-3]);
}
That or you can do a try catch to catch the error and display something like invalid choice.