Reputation: 13
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:");
}
}
Upvotes: 1
Views: 51
Reputation: 5102
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();
}
}
Upvotes: 1
Reputation: 4600
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:");
}
}
}
Upvotes: 2