简体   繁体   中英

C# Validate integer user input in class property

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM