1

I have simple function of input validation:

private static int GetInt()
{
    int tryInt;

    while (true)
    {
        if (int.TryParse(Console.ReadLine(), out tryInt)) 
            return tryInt;
        else 
            Console.Write("Try again:");
    }
}

I want to pass in criteria (let's say I want odd numbers, more than 20) How can I do it? Should I?

private static int GetInt(< criteria >)
{
    int tryInt;

    while (true)
    {
        if (int.TryParse(Console.ReadLine(), out tryInt) && < criteria >) 
           return tryInt;
        else 
           Console.Write("Try again:");
    }
}

2 Answers 2

2

Sounds like you can utilize Func delegates

Example:

using System;

public class Program
{
    public static void Main()
    {
        int number = GetInt();
        Console.WriteLine($"You entered: {number}");
        
        int number2 = GetInt(n => n > 0 && n < 100);
        Console.WriteLine($"You entered: {number2}");
        
        Func<int, bool> isPositiveCriteria = number => number > 0;
        int number3 = GetInt(isPositiveCriteria);
        Console.WriteLine($"You entered: {number3}");
    }

    private static int GetInt(Func<int, bool>? additionalValidation = null)
    {
        int tryInt;
        while (true)
        {
            Console.Write("Enter a number: ");
            if (int.TryParse(Console.ReadLine(), out tryInt) && (additionalValidation == null || additionalValidation(tryInt)))
            {
                return tryInt;
            }

            Console.WriteLine("Invalid input. Try again:");
        }
    }
}

Dotnet fiddle playground

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that exactly what I was looking for.
1

An elegant solution is using Spectre.Console NuGet package, using Text prompt which as shown accepts an int with, in this case validates the value entered is an int and the value entered here is between 1 and 10. Also uses colors to are optional.

Code written using NET 9.

internal class Prompts
{
    public static int GetInt(string title = "Enter a number") =>
        AnsiConsole.Prompt(
            new TextPrompt<int>($"[yellow]{title}[/]?")
                .PromptStyle("cyan")
                .Validate(ValidateBetweenOneAndTen)
                .ValidationErrorMessage("[red]Must be an integer[/]"));

    private static ValidationResult ValidateBetweenOneAndTen(int value) =>
        value is >= 1 and <= 10 ? 
            ValidationResult.Success() : 
            ValidationResult.Error("Must be between 1 and 10");
}

Usage:

internal partial class Program
{
    static void Main(string[] args)
    {

        var number = Prompts.GetInt();
        Console.Clear();
        AnsiConsole.MarkupLine($"[bold]You entered[/]: [yellow]{number}[/]");
        Console.ReadLine();
    }
}

1 Comment

Thank you very much for your answer! I am going to use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.