SHARE
TWEET

Untitled

a guest Mar 25th, 2019 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public interface IConstraint<T>
  2.     {
  3.         bool Satisfies(T value);
  4.     }
  5.     public class Constrained<T, Constraint>
  6.         where Constraint : IConstraint<T>, new()
  7.     {
  8.         public static bool TryCreate(T val, out Constrained<T, Constraint> result)
  9.         {
  10.             var c = new Constraint();
  11.             var success = c.Satisfies(val);
  12.             result = success ? new Constrained<T, Constraint>(val) : default;
  13.             return success;
  14.         }
  15.         private Constrained(T str)
  16.         {
  17.             Value = str;
  18.         }
  19.         public T Value { get; set; }
  20.  
  21.         public static implicit operator T(Constrained<T, Constraint> val) => val.Value;
  22.         public override string ToString() => Value.ToString();
  23.     }
  24.     public class NonEmptyStringConstraint : IConstraint<string>
  25.     {
  26.         public bool Satisfies(string value)
  27.             => !string.IsNullOrWhiteSpace(value);
  28.     }
  29.     class Program
  30.     {
  31.         static Constrained<string, NonEmptyStringConstraint> ReadNonEmptyString()
  32.         {
  33.             string str;
  34.             Constrained<string, NonEmptyStringConstraint> res;
  35.             do
  36.             {
  37.                 str = Console.ReadLine();
  38.             } while (!Constrained<string, NonEmptyStringConstraint>.TryCreate(str, out res));
  39.             return res;
  40.         }
  41.         static void Main(string[] args)
  42.         {
  43.             Console.WriteLine("What is your name? ");
  44.             var name = ReadNonEmptyString();
  45.             Console.WriteLine("What is your quest? ");
  46.             var quest = ReadNonEmptyString();
  47.             Console.WriteLine("What is your favourite colour? ");
  48.             var colour = ReadNonEmptyString();
  49.  
  50.             Console.WriteLine($"{name} is on a quest {quest} and his favourite colour is {colour}.");
  51.         }
  52.     }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top