Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace PhasmoTriviaConsole.Services;
- public class ColorCon
- {
- public static void Write(object o, ConsoleColor color)
- {
- Console.ForegroundColor = color;
- Console.Write(o);
- Console.ResetColor();
- }
- public static void WriteLine(object o, ConsoleColor color)
- {
- Console.ForegroundColor = color;
- Console.WriteLine(o);
- Console.ResetColor();
- }
- public static string GetStringFromConsole(
- string prompt,
- ConsoleColor color,
- Func<string, bool>? validator = null,
- string? errorMessage = null,
- ConsoleColor errorColor = ConsoleColor.Red)
- {
- while (true)
- {
- Write(prompt, color);
- var input = Console.ReadLine();
- if (input != null && (validator?.Invoke(input) ?? true))
- {
- return input;
- }
- WriteLine(errorMessage ?? "Bad Input, Try Again", errorColor);
- }
- }
- public static T GetFromConsole<T>(
- string prompt,
- ConsoleColor color,
- Func<T, bool>? validator = null,
- string? errorMessage = null,
- ConsoleColor errorColor = ConsoleColor.Red) where T : IParsable<T>
- {
- while (true)
- {
- Write(prompt, color);
- if (T.TryParse(Console.ReadLine(), null, out var value))
- {
- if (validator?.Invoke(value) ?? true)
- {
- return value;
- }
- WriteLine(errorMessage ?? "Invalid value, try again.", errorColor);
- continue;
- }
- WriteLine(errorMessage ?? "Invalid format, try again.", errorColor);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment