Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to deal with a position in list that doesn't exist?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading