mekasu0124

Untitled

Mar 10th, 2024
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.76 KB | None | 0 0
  1. namespace PhasmoTriviaConsole.Services;
  2.  
  3. public class ColorCon
  4. {
  5.     public static void Write(object o, ConsoleColor color)
  6.     {
  7.         Console.ForegroundColor = color;
  8.         Console.Write(o);
  9.         Console.ResetColor();
  10.     }
  11.  
  12.     public static void WriteLine(object o, ConsoleColor color)
  13.     {
  14.         Console.ForegroundColor = color;
  15.         Console.WriteLine(o);
  16.         Console.ResetColor();
  17.     }
  18.  
  19.     public static string GetStringFromConsole(
  20.         string prompt,
  21.         ConsoleColor color,
  22.         Func<string, bool>? validator = null,
  23.         string? errorMessage = null,
  24.         ConsoleColor errorColor = ConsoleColor.Red)
  25.     {
  26.         while (true)
  27.         {
  28.             Write(prompt, color);
  29.             var input = Console.ReadLine();
  30.            
  31.             if (input != null && (validator?.Invoke(input) ?? true))
  32.             {
  33.                 return input;
  34.             }
  35.  
  36.             WriteLine(errorMessage ?? "Bad Input, Try Again", errorColor);
  37.         }
  38.     }
  39.  
  40.     public static T GetFromConsole<T>(
  41.         string prompt,
  42.         ConsoleColor color,
  43.         Func<T, bool>? validator = null,
  44.         string? errorMessage = null,
  45.         ConsoleColor errorColor = ConsoleColor.Red) where T : IParsable<T>
  46.     {
  47.         while (true)
  48.         {
  49.             Write(prompt, color);
  50.             if (T.TryParse(Console.ReadLine(), null, out var value))
  51.             {
  52.                 if (validator?.Invoke(value) ?? true)
  53.                 {
  54.                     return value;
  55.                 }
  56.  
  57.                 WriteLine(errorMessage ?? "Invalid value, try again.", errorColor);
  58.                 continue;
  59.             }
  60.  
  61.             WriteLine(errorMessage ?? "Invalid format, try again.", errorColor);
  62.         }
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment