Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace Checker
- {
- public static class InputChecker
- {
- /// <summary>
- /// Checks if inputed value meets the conditions.
- /// </summary>
- /// <returns><c>true</c>, if value met the conditions, <c>false</c> otherwise.</returns>
- /// <param name="input">Input.</param>
- /// <param name="conditions">Conditions.</param>
- public static bool CheckConditions<T>(T input, params Func<T, bool>[] conditions)
- {
- foreach (Func<T, bool> condition in conditions)
- {
- if (!condition.Invoke(input))
- return false;
- }
- return true;
- }
- /// <summary>
- /// Inputs and parses the variable of type T.
- /// </summary>
- /// <returns>Variable of type T.</returns>
- /// <param name="input">Input.</param>
- /// <param name="conditions">Conditions.</param>
- public static T InputVar<T>(string input, params Func<T, bool>[] conditions)
- {
- var parser = typeof(T).GetMethod("TryParse", new[] { typeof(string), typeof(T).MakeByRefType() });
- if (parser == null)
- throw new ApplicationException($"Invalid type {typeof(T)}");
- Console.Write($"Enter {input}: ");
- object[] result = { Console.ReadLine(), null};
- while (!(bool)parser.Invoke(null, result) || !CheckConditions((T)result[1], conditions))
- {
- Console.WriteLine("Invalid input format! Try again!");
- Console.Write($"Enter {input}: ");
- result = new object[] { Console.ReadLine(), null };
- }
- return (T)result[1];
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement