Reputation: 9
Good day everyone. To my shame dont understand how to make it. I have a class like:
public class Worker
{
public int ID { get; set; }
}
And Data class with workers List. Have a method to work with it:
public Department GetWorkerByID (int id)
{
foreach (Worker worker in Workers)
{
if (worker.ID == id)
return worker;
}
return null;
{
The problem is i need to give the user ability to choose the current worker from list by its ID number and i want program to handle invalid input like random simbols, letters etc and check if the input ID is exist. Usually i use boolean property for this:
string input = Console.ReadLine();
bool isInt = int.TryParse(input, out _);
And so on. But in case with class properties it doesnt work like i expected and when i try to do this:
while (!isInt && Data.GetWorkerByID(int.Parse(input)) == null)
{
Console.Write("Wrong input. Try again: ");
input = Console.ReadLine();
}
Its not working, throwing me the exceptions of invalid format for ID number or pass the number but than trying to get the non existing instance of worker. Any advice welcome.
Upvotes: 0
Views: 403
Reputation: 79
Try do something like that:
C#:
public Worker TryGetWorker()
{
string input = Console.ReadLine();
int index = -1;
bool isInt = int.TryParse(input,out index);
Worker worker = Data.GetWorkerByID(index);
if (!isInt || worker == null)
{
Console.Write("Wrong input. Try again: ");
return TryGetWorker();
}
else
return worker;
}
Upvotes: 1