Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface IConstraint<T>
- {
- bool Satisfies(T value);
- }
- public class Constrained<T, Constraint>
- where Constraint : IConstraint<T>, new()
- {
- public static bool TryCreate(T val, out Constrained<T, Constraint> result)
- {
- var c = new Constraint();
- var success = c.Satisfies(val);
- result = success ? new Constrained<T, Constraint>(val) : default;
- return success;
- }
- private Constrained(T str)
- {
- Value = str;
- }
- public T Value { get; set; }
- public static implicit operator T(Constrained<T, Constraint> val) => val.Value;
- public override string ToString() => Value.ToString();
- }
- public class NonEmptyStringConstraint : IConstraint<string>
- {
- public bool Satisfies(string value)
- => !string.IsNullOrWhiteSpace(value);
- }
- class Program
- {
- static Constrained<string, NonEmptyStringConstraint> ReadNonEmptyString()
- {
- string str;
- Constrained<string, NonEmptyStringConstraint> res;
- do
- {
- str = Console.ReadLine();
- } while (!Constrained<string, NonEmptyStringConstraint>.TryCreate(str, out res));
- return res;
- }
- static void Main(string[] args)
- {
- Console.WriteLine("What is your name? ");
- var name = ReadNonEmptyString();
- Console.WriteLine("What is your quest? ");
- var quest = ReadNonEmptyString();
- Console.WriteLine("What is your favourite colour? ");
- var colour = ReadNonEmptyString();
- Console.WriteLine($"{name} is on a quest {quest} and his favourite colour is {colour}.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement